Python set of characteristics, the conventional method of application scenarios and
1. The basic concept set
1.1 non-repeatable set of elements inside
s = {1, 1, 1, 1, 1, 3, 5, 67, 89}
print(s,type(s))
Output:
1.2 Definitions an empty set
s1 = {}
print(type(s1)) # 默认情况下是dict
s2 = set([]) # 定义一个空集合
print(s2,type(s2))
Output:
2. Characteristics of the collection
Collection supports only member operators, for loop
2.1 member operator
s = {1,2,3}
print(1 in s)
print(1 not in s)
Output:
2.2 for loop
s = {1,2,3}
for i in s:
print(i,end='')
print()
Output:
3. The method set common
Add 3.1
A set of variable data type is
added sequentially and the order of storage is not the same
s = {4,5,6,7,8,9,2}
print(s)
#添加一个元素s.add()
s.add(10)
s.add(0)
print(s)
#添加多个元素a.update()
s.update({3,6,7,8})
print(s)
Output:
3.2 Delete
s = {4,5,6,7,8,9,2}
a = s.pop()
print(s)
print(a)
# 删除指定的元素
s.remove(9)
print(s)
Output:
3.3 Sorting
s1 = {2,3,1}
sorted(s1)
print(s1)
Output:
3.4 union
s1 = {2,3,1}
s2 = {2,3,4}
print('并集:',s1.union(s2))
print('并集:',s1 | s2)
Output:
3.5 Intersection
s1 = {2,3,1}
s2 = {2,3,4}
print('交集:',s1.intersection(s2))
print('交集:',s1 & s2)
Output:
3.6 difference set
difference set s1 and s2: s2, which elements have not s1
s1 = {2,3,1}
s2 = {2,3,4}
print('差集:',s1.difference(s2))
print('差集:',s1 -s2)
Output:
3.7 pairs of differential, etc.
Peer difference: the union - intersection
s1 = {2,3,1}
s2 = {2,3,4}
print('对等差分:',s1.symmetric_difference(s2))
print('对等差分:',s1 ^ s2)
Output:
3.8 judge
s1.issubset(s2): S1 s2 whether a subset of
s1.isdisjoint(s2): Two sets are not disjoint
s1 = {'westos','redhat','python'}
s2 = {'redhat','westos','linux'}
# s1是否是s2的子集
print(s1.issubset(s2))
# 两个集合是不是不相交
print(s1.isdisjoint(s2))
Output:
4. The set of scenarios
Quick to re-list
li = [1,2,3,4,5,6,6,6,7,8,9,9,9]
print(list(set(li)))
Output: