Python13_ collection (set)

set

Similarly dict, is a set of key not stored value

Nature: a collection of unordered and non-repeating elements

格式:集合名={元素1,元素2……,元素n}

create

Create a set must have a list or tuple as output set

Repeating element is automatically filtered in the set

s1 = set([1,2,3,4,4,5,5,5])
print(s1)   #输出{1,2,3,4,5}

s2 = set((1,2,3,4,5))
s3 = set({1:"good",2:"nice"})#只将字典中的key保存为set的元素
print(s2)
print(s3)   #只输出字典中的key

add (elementary data type / tuples)

Personal understanding: If the elements set itself can not change

s4 = set([1,2,3,4,5])
s4.add(6)   #可以添加重复的,但是没有效果
print(s4)
s4.add([9,8,7])#报错,因为set的元素不能是列表,因为列表可变
s4.add((9,8,7)) #不会报错,但是将元组作为元素
s4.add([1:"good",2:"nice"]) #报错,因为字典的元素可变,所以不能作为set的元素

update()

Insert the whole list, tuple, string, inserting break

s5 = set([1,2,3,4,5])
s5.update([6,7,8,9])
print(s5)
s5.update("sunck")
print(s5)
s5.update({1:"good",22:"nice"})
print(s5)

remove(elem)

Remove elements, if the elem does not exist, an error

s6 = set([1,2,3,4,5])
s6.remove(5)

pop()

Random delete elements, if there is no element in the collection, but also pop, it will error

格式:集合名.pop()

discard()

格式:集合名.discard(elem)

If the element is present, delete, and if not, no operation

s = {1,2,3,4}
s.discard(3)

Traversal

Cyclic

s7 = set([1,2,3,4,5])
for i in s7:
    print(i)
    

for index,data in enumerate(s7):
    print(index,data)

ps: So far, dict and set can be used enumerate () method

Intersection

s8 = set([1,2,3,4,5])
s9 = set([8,9])

a1 = s8 & s9
print(type(a1)) #set的交集还是set
print(a1)

Union

s2 = s8 | s9

ps: set with less than the actual, mostly type conversion

tuple --> set

set --> list

set --> tuple

Quite conversion and mandatory

mainly used to re-set

myList = [1,1,1,12,2,2,3,4,5,6]
print(list(set(myList)))

Guess you like

Origin blog.csdn.net/qq_34873298/article/details/89579546