data structure
There are 4 built-in data structures in python-list (list), tuple (tuple), dictionary (dictionary), set (collection), they can be collectively called "containers"
The "things" in these four "containers" can be numbers, characters, lists or a combination of them, anything is fine, and the element types are not required to be the same
1. List/tuple
Both lists and tuples are sequence structures
Shape:
list: []
tuple: ()
c = [1,'abc',[1,2]] #c是一个列表,列表的第一个元素是整数1,第二个是字符串'abc',第三个是列表[1,2]
c
Functional difference:
Lists can be modified, but tuples cannot.
a = [1,2,3]
print(a)
a[0] = 0
print(a)
b = (1,2,3)
print(b)
b[0] = 0 #修改报错
print(b)
If you already have a list a and you want to copy a and name it b, then b=a is invalid . At this time, b is just an alias (or reference) of a, and modifying b will also modify a;
if you want To copy a, use b = a[:]
a = [1,2,3]
print("原来的a:",a)
b = a
print("原来的b:",b)
b[0] = 0
print("现在的a:",a)
print("现在的b:",b)
a = [1,2,3]
print("原来的a:",a)
b = a[:]
print("原来的b:",b)
b[0] = 0
print("现在的a:",a)
print("现在的b:",b)
Function:
Convert an object into a list/tuple
List: list()
Tuple: tuple()
list('ab')
tuple([1,2])
Functions related to lists/tuples:
As an object, the list itself comes with many practical methods, tuples are not allowed to be modified, so there are few methods
The method that comes with the list itself:
#使用append函数对列表元素进行操作
a = [1,2,3]
b = []
for i in a:
b.append(i+2)
print(a)
print(b)
#使用列表解析进行简化
a = [1,2,3]
b = [i+2 for i in a]
print(a)
print(b)
2. Dictionary
"Dictionary" and lists and tuples different from its index is not zero, but their definition of keys and key must be in the whole dictionary unique in
#创建一个字典
d = {
'today':13,'tomorrow':14} #这里的today,Tomarrow就是字典的键,它在整个字典中必须是唯一的;13,14是“键”对应的值
d
#访问字典中的元素
print(d['today'])
print(d['tomorrow'])
#通过dict()或者dict.fromkeys创建字典
dict([['today',13],['tomorrow',14]]) #相当于{'today':13,'tomorrow':14}
dict.fromkeys(['today','tomorrow'],15) #相当于{'today':15,'tomorrow':15}
Many dictionary-related functions and methods are the same as lists:
3. Collection
The difference with the list: ① Its elements cannot be repeated and are unordered ; ② It does not support indexing . Create a set
through **{} or set()** functions
s = {
1,2,2,3} #注意2会自动去重,得到{1,2,3}
print(s)
t = [1,2,2,3] #将列表转换为集合,也会的到去重后的{1,2,3}
s = set(t)
print(s)
Due to the particularity of sets, sets have some special operations:
t = {
1,2,3}
s = {
1,4,5}
a = t|s #t和s的并集
b = t&s #t和s的交集
c = t-s #t和s的差集
d = t^s #t和s的对称差集(项在t或s中,但不会同时出现在二者之中)
print(a)
print(b)
print(c)
print(d)