📜  Python|设置()方法

📅  最后修改于: 2022-05-13 01:55:35.976000             🧑  作者: Mango

Python|设置()方法

Set是由不同语言组成的序列的数学术语, Python也对其语言进行了扩展,并且可以使用 set() 轻松生成。

set()方法用于将任何可迭代对象转换为具有不同元素的可迭代元素序列,通常称为 Set。

如果您从集合中获得无序列表,请不要担心。集合是无序的。使用 sorted(set(sampleList)) 对其进行排序

代码 #1:用列表和元组演示 set()

Python3
# Python3 code to demonstrate the
# working of set() on list and tuple
 
# initializing list
lis1 = [ 3, 4, 1, 4, 5 ]
 
# initializing tuple
tup1 = (3, 4, 1, 4, 5)
 
# Printing iterables before conversion
print("The list before conversion is : " + str(lis1))
print("The tuple before conversion is : " + str(tup1))
 
# Iterables after conversion are
# notice distinct and elements
print("The list after conversion is : " + str(set(lis1)))
print("The tuple after conversion is : " + str(set(tup1)))


Python3
# Python3 code to demonstrate the
# working of set() on dictionary
 
# initializing list
dic1 = { 4 : 'geeks', 1 : 'for', 3 : 'geeks' }
 
# Printing dictionary before conversion
# internally sorted
print("Dictionary before conversion is : " + str(dic1))
 
# Dictionary after conversion are
# notice lost keys
print("Dictionary after conversion is : " + str(set(dic1)))


输出:

The list before conversion is : [3, 4, 1, 4, 5]
The tuple before conversion is : (3, 4, 1, 4, 5)
The list after conversion is : {1, 3, 4, 5}
The tuple after conversion is : {1, 3, 4, 5}
set() 的属性
  • 没有传递任何参数来创建空集
  • 也可以使用 set 创建字典,但转换后只保留键,丢失值。

代码#2:字典上集合的工作演示

Python3

# Python3 code to demonstrate the
# working of set() on dictionary
 
# initializing list
dic1 = { 4 : 'geeks', 1 : 'for', 3 : 'geeks' }
 
# Printing dictionary before conversion
# internally sorted
print("Dictionary before conversion is : " + str(dic1))
 
# Dictionary after conversion are
# notice lost keys
print("Dictionary after conversion is : " + str(set(dic1)))
输出
Dictionary before conversion is : {4: 'geeks', 1: 'for', 3: 'geeks'}
Dictionary after conversion is : {1, 3, 4}

时间复杂度: Set 方法实现为哈希表,因此时间复杂度为O(1)