Difference between Python list and dictionary

Reference in Python lists and dictionaries What is the difference? Learning records made.

List

The list is "heterogeneous" and can contain different types of objects

l = [1, [2.3, 4]'temp']

The list is "ordered", sliced, left closed and right open

l = [1,2,3,4,5,6,7]
l[1:4] = [2,3,4]
//1:4表示序号1到序号4,序号为1的为2,序号为4的为5,根据左闭右开,所以为[2,3,4]
l[1:] = [2,3,4,5,6,7]
l[:6] = [1,2,3,4,5,6]
l[:7] 报错SyntaxError: invalid character in identifier,超出最大序号了
l[:] = list

Negative index

l = [1,2,3,4,5,6,7]
l[2:-1] = [3,4,5,6]//2代表起始序号(正序),-1代表末序号(逆序) ,即序号为6也是-1,序号为5也是-2

Step slicing

l = [1,2,3,4,5,6,7]
l[0::2] = [1,3,5,7]//0代表起始序号,2代表步进
l[1::3] = [2,5]

List insertion, modification and deletion do not need to rebuild the table

***********插入
l = [1,2,3,4,5,6,7] 
l.append(8)//在尾部插入
print(l) //[1,2,3,4,5,6,7,8]
l.insert(1,1.5)//1代表插入位置,插入1.5
print(l)//[1,1.5,2,3,4,5,6,7,8]
l.insert(10,11)//插入位置大于列表长度,则在末尾插入
print(l)//[1,1.5,2,3,4,5,6,7,8,11]
l.extend([12,13,14])//同时在尾部插入多个元素
print(l)//[1,1.5,2,3,4,5,6,7,8,11,12,13,14]
***********修改
l = [1,2,3,4,5]
l[0] = "?"
print(l)//['?',2,3,4,5]
l[0:2] = ['a,'b']
print(l)//['a','b',3,4,5]
***********删除
l = [1,2,3,1]
l.remove(1)
print(l)//[2,3,1],默认删除第一个1
l = [1,2,3,1]
del l[3:]//del是python的一个内置函数,可依切片删除,也可以删除多个元素
print(l)//[1,2,3]
l.pop()//返回最后一个元素的值3,有点像栈顶出栈
print(l)//[1,2]

Sort

l = [2,1,3,4,5,6,7,8,11,12,13,14]
l.sort()
print(l)//[1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14]
l.reverse()
print(l)//[14, 13, 12, 11, 8, 7, 6, 5, 4, 3, 2, 1]

dictionary

A dictionary is completely different from a list. It contains a pair of key values, and each key is unique. Index by position instead of by key instead of list. Heterogeneous disorder .

Dic = {
    
    'color':'red',
	   'num':1,
	   'list':[1,3,4],
       'gender':{
    
    '男':1,'女':2}
       }

Read

print(Dic['color'])//red

insert

Dic['alibaba'] = 1
Dic['num'] = 2
print(Dic)	
		//{'color':'red',
	   //'num':2,
	   //'list':[1,3,4],
      // 'gender':{'男':1,'女':2},
       //'alibaba':1
      // }

Use a list to generate a dictionary

a = ['one','two','three']
b = [1,2,3]
Dic = dict(zip(a,b))
print(Dic)//{'one': 1, 'two': 2, 'three': 3}

Use key-value pairs to form a dictionary

Dic = dict([('a',1),('b',2)])
print(Dic)//{'a':1, 'b': 2}

Get key value

Dic = {
    
    'a':1,'b':2}
print(list(Dic.keys()))//['a', 'b']
print(list(Dic.values()))//[1,2]
print(list(Dic.items()))//[('a', 1), ('b', 2)]
//list是列表方法,注意不要定义list = []形式的列表,否则会报错TypeError: 'list' object is not callable

Delete key

Dic = {
    
    'a':1,'b':2}
del D['a']
print(Dic)//{'b': 2}
Dic = {
    
    'a':1,'b':2}
print(Dic.pop('a'))//1
print(Dic)//{'b':2}

Sort

The sorting of the dictionary is actually the sorting of the keys

Dic = {
    
    'color':'red',
	   'num':1,
	   'list':[1,3,4],
       'gender':{
    
    '男':1,'女':2}
       }
sorted(Dic)//'color', 'gender', 'list', 'num']

Guess you like

Origin blog.csdn.net/qq_16488989/article/details/109378435