python container set

set
Set is similar to list and has a series of elements.
Difference: elements in set are not allowed to be repeated, while lists can contain the same elements; elements in set are not ordered.
The way to create a set is to use set() and pass in a list. The elements of the list will be converted into elements of the
set. The elements of the set are case sensitive.

s = set([1, 4, 3, 2, 5, 4, 2, 3, 1])
print(s) #{1, 2, 3, 4, 5}
read element
1 in s
add element

names = []
names_set = set(names)
##Add a single
name_set.add('Jenny')
names_set.add('Ellena')
print(names_set)##{'Jenny','Ellena'}
##Add
new_names in batch = ['Jenny','Ellena','Alice','Candy','David','Hally','Bob','Isen','Karl']
names_set.update(new_names)
print(names_set) ## {'Bob','Hally','Ellena','Jenny','Candy','Isen','Karl','Alice','David'}
Delete elements
L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
S = set([1, 3, 5, 7, 9, 11])
for elem in L:
if elem not in S:
S.add(elem)
else:
S .remove(elem)
print(S)
delete method without error discard()
method to clear all elements clear()
subset and superset of the collection
Set provides methods to determine the relationship between two sets, such as two sets, to determine whether one set is a subset or superset of the other set.

s1 = set([1, 2, 3, 4, 5])
s2 = set([1, 2, 3, 4, 5, 6, 7, 8, 9])

Determine whether s1 is a subset of s2

s1.issubset(s2) # ==> True

Determine whether s2 is a superset of s1

s2.issuperset(s1) # ==> True to
judge whether the set
overlaps s1.isdisjoint(s2) # ==> False, because there are duplicate elements

s1 = set([1, 2, 3, 4, 5])
s2 = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
flag = s1.isdisjoint(s2)## 判断 s1是否和 s2有重合元素  返回false
if not flag:
    for elem1 in s1:
        if elem1 in s2:##将s1中元素与s2元素一一比对
            print(elem1)##1 2 3 4 5 将重合元素打印出来

Guess you like

Origin blog.csdn.net/angelsweet/article/details/109194816