python class finishing 7 --- collection

The previous section:

to control interval between symbols sep each element

print("alex", "dabai", "liu", sep = "")

At the variable immutable:

1. Variable: lists, dictionaries

2. immutable: string, number, tuple

Modify the value of the variable, and the change with id number, i.e., immutable type

name = 'alex'
print(id(name))
name = 'sb'
print(id(name))

Access sequence:

1. sequential access: strings, lists, tuples

2. Mapping: Dictionary

3. Direct Access: Digital

Store the number of elements:

Container types: lists, tuples, dictionaries

Atoms: number, string

#################set###################

A collection set

1. Different elements

2. disorder

3. collection element must be immutable

s = {1, 2, 3, 4, 5}

Built-in functions: set () is also simple to re-effect, if the order does not care

s = set('hello')
print(s)
s1 = set(["alex", "alex", "sb"])
print(s1)

Second, a set of magic

1. add, add an element to the collection (only update one)

s = {1, 2, 3, 4, 5, 6}
s.add('alex')
print(s)

2. clear Empty collection

s.clear()

3. Copy set

s1 = s.copy()

4. pop randomly remove elements

s = {1, 2, 3, 4, 5, 6} 
v = s.pop () 
print (s, v)

5. remove the specified element deleted, an error when deleting element does not exist

s = {1, 2, 3, 4, 5, 6}
s.remove(3)
print(s)

6. discard specified element deleted, but to delete the element does not exist error

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

7. Intersection

s1 = {1, 2, 3}
s2 = {2, 3, 4, 6}
n = s1.intersection(s2)
print(n)

or:&

s1 = {1, 2, 3}
s2 = {2, 3, 4, 6}
n = s1 & s2
print(n)

8. Set and

s1 = {1, 2, 3}
s2 = {2, 3, 4, 6}
n = s1.union(s2)
print(n)

Or: |

s1 = {1, 2, 3}
s2 = {2, 3, 4, 6}
n = s1 | s2
print(n)

9. differencing sets (s1 and s2 have no)

s1 = {1, 2, 3}
s2 = {2, 3, 4, 6}
n = s1.difference(s2)
print(n)

or:-

s1 = {1, 2, 3}
s2 = {2, 3, 4, 6}
n = s1 - s2
print(n)

 10.交叉补集(s1 和 s2 的全部,减去两者的交集)

s1 = {1, 2, 3}
s2 = {2, 3, 4, 6}
n = s1.symmetric_difference(s2)
print(n)

或者   ^

s1 = {1, 2, 3}
s2 = {2, 3, 4, 6}
n = s1 ^ s2
print(n)

11.更新差集

s1 = {1, 2, 3}
s2 = {2, 3, 4, 6}
s1.difference_update(s2)
s1 = s1 - s2
print(s1)
print(s1)

12. s1 是否是s2的子集

s1 = {1, 2, 3}
s2 = {1, 2, 3, 4, 6}
n = s1.issubset(s2)
print(n)

13. s2是否是s1的父集

s1 = {1, 2, 3}
s2 = {1, 2, 3, 4, 6}
n = s2.issuperset(s1)
print(n)

14. 更新多个值,参数可以是列表、元组等

s1 = {1, 2, 3}
s2 = {1, 2, 3, 4, 6}
s1.update(s2)
print(s1)

15. 定义一个不可变的集合(不能增删改)

s = frozenset("hello dabai")
print(s)

Guess you like

Origin www.cnblogs.com/dabai123/p/10984879.html