030 built-in method of collection

Collection type of built-in method

集合可以理解成一个整体,学习Python的学生可以是一个集合体;学习Linux的学生可以是一个集合体

pythoners = ['jason', 'nick', 'tank', 'sean']
linuxers = ['nick', 'egon', 'kevin']

# 即报名pythoners又报名linux的学生
py_li_list = []
for stu in pythoners:
    if stu in linuxers:
        py_li_list.append(stu)
print(f"pythoners and linuxers: {py_li_list}")

# pythoners and linuxers: ['nick']

1. Use

集合用于关系运算的结合体,由于集合内的元素无序且集合元素不可重复,因此集合可以去重,但是去重后的集合会打乱原来元素的顺序。

2. Definitions

在{}内用逗号分隔开多个元素,每个元素必须是不可变类型

age = {18,12,9,21,22}
name = {'nick','egon','rocky'}

3. The method of common operations built +

**优先掌握**

1.长度len

2.成员运算in/not in

3.|并集、union

4.&交集、intersection

5.-差集、difference

6.补集、symmetric_difference

1. The length len

hobby_set = {'run','read','paly'}
print(len(hobby_set))
# 3

2. Members in operation and not in

hobby_set = {'run','read','paly'}
print('swim' in hobby_set)
# False

print('run' in hobby_set)
# True

3. | union (union)

hobby_set = {'run','read','paly'}
hobby_set2 = {'run','sing','swim'}

print(hobby_set | hobby_set2)
# {'paly', 'swim', 'read', 'run', 'sing'}

print(hobby_set.union(hobby_set2))
# {'read', 'sing', 'run', 'swim', 'paly'}

4. & intersection (intersection)

hobby_set = {'run','read','paly'}
hobby_set2 = {'run','sing','swim'}

print(hobby_set & hobby_set2)
# {'run'}

print(hobby_set.intersection(hobby_set2))
# {'run'}

5.-差集(difference)

hobby_set = {'run','read','paly'}
hobby_set2 = {'run','sing','swim'}

print(hobby_set - hobby_set2)
# {'read', 'paly'}

print(hobby_set.difference(hobby_set2))
# {'read', 'paly'}

6.^补集(symmetric_difference)

hobby_set = {'run','read','paly'}
hobby_set2 = {'run','sing','swim'}

print(hobby_set ^ hobby_set2)
# {'swim', 'sing', 'paly', 'read'}

print(hobby_set.ymmetric_difference(hobby_set2))
# {'swim', 'sing', 'paly', 'read'}

**了解**

1.pop随机删除

2.clear清空

3.update更新

4.copy复制

5.移除remove/discard

remove and discard the difference between:

remove when removing an element of the collection is not, the program reports an error and does not discard error

4 is a set of a plurality of stored values

The sets are unordered

6. The set of variable data type

Guess you like

Origin www.cnblogs.com/xichenHome/p/11304924.html