The basic usage of the collection of python must be series

1: Declaration of the collection (how to define a collection)

##集合的关键字为set,集合的最大的特点就是不能有重复的元素
s1 = set()  ##创建空集合,只能用set

s1 = {1,2,3}  ##字典 {key:value,key:value}   集合 {元素1,元素2,元素3}

Example: Quickly de-duplicate a list

###给列表去重排序的方法:

list1 = [1,4,5,2,2,4,5,7,3,6,8]
set1 = set(list1)  ##将一个列表转换成一个集合进行去重操作,并且如果列表中都是数字的话还会进行一个排序的操作
list2 = list(set1) ##将得到的列表重新转换成一个列表
print(list2)


{1, 2, 3, 4, 5, 6, 7, 8}
[1, 2, 3, 4, 5, 6, 7, 8]

1: Add operation to the list

add command

s1 = set()
s1.add("hello")
s1.add("小猪佩奇")
print(s1)

{'hello', '小猪佩奇'}

update operation, you can add multiple operations at once

s1 = set()
s1.add("hello")
s1.add("小猪佩奇")
print(s1)

s2 = {"yz","超级赛亚人"}
s1.update(s2)   ##随机插入的
print(s1)

{'hello', '小猪佩奇'}
{'hello', '超级赛亚人', 'yz', '小猪佩奇'}

2: The delete operation of the collection

1:remove method, specify the element to be deleted

s1= {'hello', '超级赛亚人', 'yz', '小猪佩奇'}
s1.remove('yz')
print(s1)

{'超级赛亚人', '小猪佩奇', 'hello'}

2: pop method: delete randomly, but usually delete the first element

s1= {'hello', '超级赛亚人', 'yz', '小猪佩奇'}
s1.pop()
print(s1)


{'小猪佩奇', 'yz', 'hello'}

3: The clear method clears the collection

s1= {'hello', '超级赛亚人', 'yz', '小猪佩奇'}
s1.clear()
print(s1)

set()

Example 1: Generate 10 random numbers from 1 to 20, and remove the duplicates

import random
list1 = []
for i  in range(20):
    num = random.randint(1,20)
    list1.append(num)
    list2 = list(set(list1))
print(list1)
print(list2)

##使用if判断语句也可以,判断每次随机产生的数据是否已经在列表中了


[1, 11, 18, 1, 18, 16, 6, 14, 19, 6, 11, 15, 18, 7, 15, 11, 5, 5, 17, 9]
[1, 5, 6, 7, 9, 11, 14, 15, 16, 17, 18, 19]

 

The difference of the list (-) difference is  in set2 but not in set1

set1={1,2,3,4,5,6}
set2={1,2,3,4,5,6,7,8}
set3 = set2 -set1
print(set3)

set4= set2.difference(set1)
print(set4)

{8, 7}
{8, 7}

The intersection of the list (&) intersection

set1={1,2,3,4,5,6}
set2={1,2,3,4,5,6,7,8}
set3 = set2 & set1
print(set3)

{1, 2, 3, 4, 5, 6}


set1={1,2,3,4,5,6}
set2={1,2,3,4,5,6,7,8}
set3=set2.intersection(set1)
print(set3)

{1, 2, 3, 4, 5, 6}

Union of sets (|) union

set1={1,2,3,4,5,6}
set2={1,2,3,4,5,6,7,8}
set3 = set1 | set2
print(set3)

{1, 2, 3, 4, 5, 6, 7, 8}

set1={1,2,3,4,5,6}
set2={1,2,3,4,5,6,7,8}
set3 = set2.union(set2)
print(set3)

{1, 2, 3, 4, 5, 6, 7, 8}

Symmetric difference set (^)

symmetric_difference()

Different elements in two sets

 

Example: Find the same elements and different elements in two lists

1: Find the same elements

list1=[1,3,4,5,6,7,8]
list2=[2,4,5,6,8,3,1,5]
s1 = set(list1)
s2 = set(list2)
s3 = s2 & s1
list3 = list(s3)
print(list3

[1, 3, 4, 5, 6, 8]

2: Find out the different elements in the two lists

list1=[1,3,4,5,6,8,7]
list2=[2,4,5,6,8,3,1,5]
s1 = set(list1)
s2 = set(list2)
s3 = s2 ^ s1
list3 = list(s3)
print(s3)

{2, 7}

 

 

 

Guess you like

Origin blog.csdn.net/yinzhen_boke_0321/article/details/104555631