在python3中,用花括号{ }括起来的数据如果没有体现映射关系,即表示这个是一个集合,type为 set
set 集合中的数据是无序的, 对列表顺序有需求的话,不建议使用set
a = {1, 2, 3, 3, 4, 5, 4, 0}1、将集合转化为list: list(set(a)) 或 list(a)
2、用传统方式达到和set的效果(去重):
temp = []
for each in a:
if each not in temp:
temp.append(each)
print(temp)3、可使用 in、not in 判断某一个数据在集合中是否存在
print(2 in a) #True
print(8 not in a) #True
print('2' in a) #False4、向集合中add、remove 数据
a.add(11)
a.remove(2)5、将集合设置为不可变结合 forzenset()
b = frozenset(temp)
#b将不支持add、remove方法
本文详细介绍了Python3中set集合的基本操作方法,包括集合的创建、转换为列表、去重、元素查找、添加及删除等常用操作,并通过实例展示了如何利用集合解决实际问题。
1927

被折叠的 条评论
为什么被折叠?



