python xx004集合

#集合里的元素是唯一的,重复的元素会被去除,fozenset()创建不可变集合

>>> num = {}  # 空花括号为字典
>>> type(num)
<class 'dict'>
>>> num = {1, 2, 3, 4, 5}  # 花括号内元素没有映射关系为集合
>>> type(num)
<class 'set'>
>>> set1 = set({1, 2, 3, 4, 5, 5, 0})  # set(列表/元组等)创建集合,括号内只能传入一个参数且参数为可迭代的,1个列表为1个参数,1个元组为一个参数
>>> set1
{0, 1, 2, 3, 4, 5}
>>> l = [1, 2, 3, 4, 5, 5, 0]
>>> temp = []
  # 去除l列表中重复的元素
>>> for each in l:
        if each not in temp:
            temp.append(each)
>>> temp
[1, 2, 3, 4, 5, 0]
  # 使用集合去除l列表中重复的元素
>>> temp2 = list(set(l))
>>> temp2
[0, 1, 2, 3, 4, 5]
  # 将l列表转换为集合
>>> set(l)
{0, 1, 2, 3, 4, 5}
  # frozen(冰冻的,冻结的)创建不可变集合
>>> notchange = frozenset({1, 3, 4, 5})
>>> notchange
frozenset({1, 3, 4, 5})
  # add方法增加元素到frozen创建的不可变集合会报错
>>> notchange.add({6})
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    notchange.add({6})
AttributeError: 'frozenset' object has no attribute 'add'

猜你喜欢

转载自www.cnblogs.com/joeshang/p/12639108.html
今日推荐