[Collection] variables

Variables : used to record the status change.

Basic types : strings, numbers, lists, tuples, dictionaries.

Category : variable and immutable

Thus Visible: Character string type is immutable (assign a new value when the address has changed)

This shows that: the list is variable (change the value of the same address)

Similarly, digital, immutable tuple type, variable type dictionary.


Access sequence:

Direct access to the (variable name): Digital

Sequential access (index): strings, lists, tuples

Mapping (key - value pairs): Dictionary


 Can be divided into:

Container type (can store multiple values): a list of tuples, dictionaries

Atom type (store only one value): number, string


 set:

The method defined : between the braces separated by commas, elements:

set()

Disorderly;

Of different elements;

The collection element must be immutable;

 

 Simple:

s.pop (): random delete

s.remove (): Delete the collection does not exist error will elements

s.discard (): Delete the collection does not exist elements not being given

 

A set of relational operators: intersection, union, difference sets, etc.

1 python_1 = ['chen','sun','li','liu']
2 linux_1 = ['liu','sun','cris']
3 p_s = set(python_1) #转集合,依次遍历列表,将不相同的元素存放在集合中,顺序已改变
4 l_s = set(linux_1)
5 print(p_s&l_s)      #求交集
6 print(p_s.intersection(l_s)) #求交集
7 
8 >>{'liu', 'sun'}
9 >>{'liu', 'sun'}
1 print(p_s.union(l_s))  #求并集
2 print(p_s|l_s)         #求并集
3 
4 >>{'cris', 'sun', 'li', 'liu', 'chen'}
5 >>{'cris', 'sun', 'li', 'liu', 'chen'}
1 print(p_s-l_s)   #求差集
print(p_s.difference(l_s))
2 >>{'chen', 'li'}
1 #交叉补集(并-交)
2 print(p_s.symmetric_difference(l_s))
3 print(p_s^l_s)
4 >>>{'cris', 'chen', 'li'}
5 >>>{'cris', 'chen', 'li'}
1 s1 = {2,3,4}
2 s2 = {'s',9,0}
3 print(s1.isdisjoint(s2)) #两个集合交集为空返回True
4 >>>True
1 s1 = {1,2,3,4}
2 s2 = {1,2}
3 print(s2.issubset(s1))  #s2是s1的子集返回True
4 print(s1.issuperset(s2))#s1是s2的父集返回True
5 >>>True
6 >>>True
1 python_1 = ['chen','sun','li','liu']
2 linux_1 = ['liu','sun','cris']
3 p_s = set(python_1)
4 l_s = set(linux_1)
5 p_s.difference_update(l_s)   #p_s=p_s-l_s
6 print(p_s)
7 >>>{'li', 'chen'}
1 s1 = {2,3,4}
2 s2 = {5,6,2}
3 s1.update(s2) #更新多个值
4 #s1.add(5)    #更新一个值
5 #s1.union(s2) #不更新
6 s1
7 >>>{2, 3, 4, 5, 6}

可以看出:集合为可变类型。

1 s = frozenset('hello')   #不可变集合
2 s.add(1)
3 >>>AttributeError: 'frozenset' object has no attribute 'add'

 2019-06-11 22:00:28

Guess you like

Origin www.cnblogs.com/direwolf22/p/11006385.html