标签:如何 不可变 indexing -- tee remove 直接 style col
>>> num = {}
>>> type(num)
<class ‘dict‘>
>>> num2 = {1,2,3,4,5}
>>> type(num2)
<class ‘set‘>
>>> num2
{1, 2, 3, 4, 5}
>>> num2[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ‘set‘ object does not support indexing
如何创建一个集合
一种时直接把一堆元素用花括号括起来
一种是使用set()工厂函数
set()得到的数据是无序的
>>> set1 = set([1,2,3,4,5,6,6])
>>> set1
{1, 2, 3, 4, 5, 6}
去重复元素
>>> set1 = set([1,2,3,4,5,6,6])
>>> set1
{1, 2, 3, 4, 5, 6}
>>> num1 = [1,2,3,4,5,6,4,2,1,0]
>>> temp = []
>>> for each in num1:
... if each not in temp:
... temp.append(each)
...
>>> temp
[1, 2, 3, 4, 5, 6, 0]
>>> num1 = list(set(num1))
>>> num1
[0, 1, 2, 3, 4, 5, 6]
in not in
>>> 1 in num1
True
>>> ‘1‘ in num1
False
add() remove()
>>> num2
{1, 2, 3, 4, 5}
>>> num2.add(‘12‘)
>>> num2
{1, 2, 3, 4, 5, ‘12‘}
>>> num.remove(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ‘dict‘ object has no attribute ‘remove‘
>>> num2.remove(5)
>>> num2
{1, 2, 3, 4, ‘12‘}
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‘
标签:如何 不可变 indexing -- tee remove 直接 style col
原文地址:http://www.cnblogs.com/fengjunjie-w/p/7496869.html