python如何创建集合,有几种方法?

604 阅读2分钟

Python集合又是一种新的数据类型,集合有两种形式:可变集合set()和不可变集合frozenset()两种,这两种集合操作方法比较类似,但是在底层性质上有截然想法的区别。集合是一种无序的,不重复且不可随机访问的元素集合,在概念和运算上和数学中的集合类似,集合分为可变和不可变两种。

一、对比数据类型****

下面是我们学习过的一些数据类型,下面的注释是对比这些数据类型的结果,供学习集合前的参考。

str1 = 'pythonpython'  # 不可变,有序:可以通过下标访问
list1 = [1232]  # 可变,有序:可以通过下标访问
tup1 = (1232)  # 不可变,有序:可以通过下标访问
dict1 = {'name''Tom''age'18'love''python'}  # 可变,无序:但可以通过键访问

二、可变集合构造方法****

1.直接构造****

set2 = {'name'19'python'}
print(set2, type(set2))

返回结果:

{19, 'python', 'name'} <class 'set'>

2.使用函数构造****

str1 = 'pythonpython'
list1 = [1232]
tup1 = (1232)
dict1 = {'name''Tom''age'18'love''python'}
set3 = set(str1)
print(set3, type(set3))
set4 = set(list1)
print(set4, type(set4))
set5 = set(tup1)
print(set5, type(set5))
set6 = set(dict1)
print(set6, type(set6))

返回结果:

{'t', 'n', 'p', 'o', 'h', 'y'} <class 'set'>
{1, 2, 3} <class 'set'>
{1, 2, 3} <class 'set'>
{'love', 'name', 'age'} <class 'set'>

3.使用推导式构造集合****

set7 = set(i for i in range(15))
print(set7, type(set7))
set8 = {i for i in list1}
print(set8, type(set8))
set8 = {i for i in tup1}
print(set8, type(set8))

返回结果:

{1, 2, 3, 4} <class 'set'>
{1, 2, 3} <class 'set'>
{1, 2, 3} <class 'set'>

三、不可变集合的构造方法****

不可变集合构造(与可变集合类似,把set改为frozenset即可)。

1.使用frozenset()函数构造****

set3 = frozenset(str1)
print(set3, type(set3))
set4 = frozenset(list1)
print(set4, type(set4))
set5 = frozenset(tup1)
print(set5, type(set5))
set6 = frozenset(dict1)
print(set6, type(set6))

  返回结果:

frozenset({'p', 'n', 't', 'h', 'y', 'o'}) <class 'frozenset'>
frozenset({1, 2, 3}) <class 'frozenset'>
frozenset({1, 2, 3}) <class 'frozenset'>
frozenset({'name', 'age', 'love'}) <class 'frozenset'>

2.推导式构造****

set7 = frozenset(i for i in range(15))
print(set7, type(set7))

返回结果:

frozenset({1, 2, 3, 4}) <class 'frozenset'>

四、集合构造注意事项****

1.集合不能想其他数据集一样使用特有的符号来构造,集合使用的语法符号是{},和字典是一样的,这时候直接使用{}来构造的,系统无法判断数据类型是字典还是集合,会默认为集合。

set9 = {}
print(type(set9))  # 默认为字典:<class 'dict'>

正确的方法只有使用构造函数来实现了。

set9 = set()
set99 = frozenset()

2.集合中不能包含字典和列表这样的可变类型元素

set10 = {'name'19, [1232]} 

列表不可哈希:TypeError: unhashable type: 'list'

以上是可变集合和不可变集合的构造方法讲解,当然也是有配套视频讲解的,或许新手看视频会更好吸收消化一些,视频在python自学网(www.wakey.com.cn) , 感兴趣的可以去看看。