030 集合的內置方法

集合類型的內置方法

集合能夠理解成一個總體,學習Python的學生能夠是一個集合體;學習Linux的學生能夠是一個集合體python

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.用途

集合用於關係運算的結合體,因爲集合內的元素無序且集合元素不可重複,所以集合能夠去重,可是去重後的集合會打亂原來元素的順序。linux

2.定義

在{}內用逗號分隔開多個元素,每一個元素必須是不可變類型app

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

3.經常使用操做+內置方法

**優先掌握**學習

1.長度lencode

2.成員運算in/not inrem

3.|並集、unionio

4.&交集、intersectionclass

5.-差集、differencedate

6.補集、symmetric_difference數據類型

1.長度len

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

2.成員運算in和not in

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

print('run' in hobby_set)
# True

3.|並集(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)

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和discard的區別:

remove在移除集合裏沒有的元素的時候,程序會報錯,而discard不會報錯

4.集合也是存多個值的

5.集合是無序的

6.集合是可變數據類型

相關文章
相關標籤/搜索