Explanation of Python collections, some public relations methods

Use of collections

-The collection is also wrapped in {}, the collection is a non-repetitive and unordered, all collections are generally used for deduplication operations
- Note: empty collections are represented by set(), {} represents an empty dictionary

persons = {
    
    'zhangsan', 'lisi', 'jack', 'lisi', 'jack', 'wangwu', 'maliu'}
print(persons) # {'zhangsan', 'wangwu', 'jack', 'maliu', 'lisi'}

persons.add('李白')  # 添加一个元素,但位置不确定,所有你们运行的答案和我的一样但是顺序不一样
print(persons)# {'zhangsan', 'wangwu', 'jack', 'maliu', 'lisi', '李白'}

persons.pop()# 随机删除一个元素,你们运行的答案应该和我的应该不一样
print(persons)  # {'wangwu', 'zhangsan', '李白', 'jack', 'maliu'}

persons.remove('李白')# 删除一个指定的元素,没有的话会报错
print(persons)  # {'wangwu', 'zhangsan', 'jack', 'maliu'}

# union 将多个集合合并生成一个新的集合
# A.update B 将B拼接到A,B要是一个可迭代对象
# 集合是无序的,所以就不一定是添加在最后
persons.update(('刘能','赵四'))
print(persons)# {'刘能', 'wangwu', 'zhangsan', '赵四', 'jack', 'maliu'}

# persons.clear()#用来清空集合的

The set in python also has the intersection, union and difference. Of course, the intersection, union and difference can also be represented by a dictionary method. I will not demonstrate it here. I feel that it is simpler to use symbols directly. If you want to understand it, You can check the help document

sing = {
    
    '王昭君', '貂蝉', '小乔', '大桥', '火舞', '李白', '韩信'}
dance = {
    
    '李元芳', '王昭君', '李白', '韩信', '老虎', '鲁班', '后裔'}
print(sing - dance)#A和B的差集 {'大桥', '火舞', '小乔', '貂蝉'}
print(sing & dance)#A和B的交集 {'王昭君', '李白', '韩信'}
print(sing | dance)#A和B的并集 {'李元芳', '王昭君', '后裔', '鲁班', '老虎', '火舞', '貂蝉', '李白', '大桥', '小乔', '韩信'}
print(sing ^ dance)#A和B的差集的并集 #{'李元芳', '鲁班', '小乔', '后裔', '火舞', '貂蝉', '老虎', '大桥'}

Some public relations methods

# +:可以用来拼接,字符串,列表,元组
print('hello' + 'world')# 'helloworld'
print([1, 2, 3] + [4, 5, 6])# [1, 2, 3, 4, 5, 6]
print((1, 2, 3) + (4, 5, 6))# (1, 2, 3, 4, 5, 6)

# -:只能用于集合,求差集
print({
    
    1,2,3}-{
    
    3})# {1, 2}

# *:可以用于字符串元组列表,不能用于字典和集合
print('hello'*3)# 'hellohellohello'
print([1,2,3]*3)# [1, 2, 3, 1, 2, 3, 1, 2, 3]
print((1,2,3)*3)# (1, 2, 3, 1, 2, 3, 1, 2, 3)

# in:成员运算符
print('a'in 'abc')# True
print(1 in[1,2,3])# True
print(1 in (1,2,3))#True
# in用于字典是用来判断key是否存在的
print('zhangsan'in{
    
    'name':'zhangsan','age':18})# False
print('name'in{
    
    'name':'zhangsan','age':18})# True

Guess you like

Origin blog.csdn.net/hmh4640219/article/details/112600194