Python:集合

xiaoxiao2021-02-28  149

字典的表亲——集合set

>>> num = {} >>> type(num) <type 'dict'> >>> num = {1,2,3,4,4} >>> type(num) <type 'set'> >>> num set([1, 2, 3, 4])

特点:元素唯一、无序不支持索引

使用set()f方法:

>>> s = set([1,2,3,4,5,5]) >>> s {1, 2, 3, 4, 5}

访问集合中的值:

用for遍历一个一个读取出来

用in    not in判断是否在

应用:

1、去掉list里的重复元素

使用遍历 >>> num = [1,2,3,4,5,5,6,6,7,8] >>> temp = [] >>> for each in num: ... if each not in temp: ... temp.append(each) ... >>> temp [1, 2, 3, 4, 5, 6, 7, 8] >>> #使用set方法 >>> num = list(set(num)) >>> num [1, 2, 3, 4, 5, 6, 7, 8] #list把无序的集合转化为列表时便宜她和你给顺序化了 内建方法:

num.add(6)

num.remove(5)

不可变集合

不可以随意的删除或增加集合中的元素

frozen:冰冻的,冻结的

>>> num3 = frozenset([1,2,3,4,5]) >>> num3.add(6) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'frozenset' object has no attribute 'add' >>>

转载请注明原文地址: https://www.6miu.com/read-25253.html

最新回复(0)