集合
构建集合
a = {"John", "Tom"} # {'Tom', 'John'}
# duplicate values will be merged
b = {"John", "Tom", "John"} # {'Tom', 'John'}
# from a list or any other iterable collection
c = set([1, 3, 5]) # {1, 3, 5}
# from set comprehension
d = {x for x in range(10)} # {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
遍历元素
a = {"fig", "mango", "watermelon"}
for e in a:
print(e)
添加元素
a = {"fig", "mango", "watermelon"}
a.add("grape")
print(a) # {'grape', 'fig', 'mango', 'watermelon'}
检查元素是否存在
a = {"fig", "mango", "watermelon"}
print("fig" in a) # True
print("cherry" in a) # False
集合常见方法
clear 清空
a = {"fig", "mango", "watermelon"}
a.clear()
print(a) # set()
difference 差集
a = {"fig", "mango", "watermelon"}
b = {"mango", "blueberry"}
# fruit in a but not in b
print(a.difference(b)) # {'watermelon', 'fig'}
print(a - b) # {'watermelon', 'fig'}
intersection 交集
a = {"fig", "mango", "watermelon"}
b = {"mango", "blueberry"}
# fruit in both a and b
print(a.intersection(b)) # {'mango'}
print(a & b) # {'mango'}
isdisjoint 是否不相交
a = {1, 3, 5}
b = {2, 4}
c = {1, 6}
print(a.isdisjoint(b)) # True
print(a.isdisjoint(c)) # False
issubset 是否子集
a = {1, 3, 5}
b = {2, 4}
c = {1, 3}
print(b.issubset(a)) # False
print(c.issubset(a)) # True
symmetric_difference 对称差集
a = {"fig", "mango", "watermelon"}
b = {"mango", "blueberry"}
# fruit in a or b but not both
print(a.symmetric_difference(b)) # {'fig', 'blueberry', 'watermelon'}
print(a ^ b) # {'fig', 'blueberry', 'watermelon'}
union 并集
a = {"fig", "mango", "watermelon"}
b = {"mango", "blueberry"}
# fruit in a or b or both
print(a.union(b)) # {'watermelon', 'blueberry', 'mango', 'fig'}
print(a | b) # {'watermelon', 'blueberry', 'mango', 'fig'}
代码挑战
编辑编辑器中代码构造一个集合:
{frozenset({'bar', 'foo', 'baz'}), 1}
。
Loading...
> 此处输出代码运行结果