导航

Python中多个列表与字典的合并方法

Posted on 2018-10-08 15:05  狼族的后裔_西伯利亚狼  阅读(1411)  评论(0编辑  收藏  举报

Python中多个列表与字典的合并方法

1多列表的合并

1)a+=b

a=['1','2','3']
b = ['22','55','66']
a += b
print(a)




>>>['1','2','3','22','55','66']

2) a.extend(b)

a=['1','2','3']
b = ['22','55','66']
a.extend(b)
print(a)


>>>['1','2','3','22','55','66']

3) a[0:0] = b切片的方法

a=['1','2','3']
b = ['22','55','66']
a[len(a):len(a)] = b
print(a)


>>>['1','2','3','22','55','66']

2 多字典的合并

1) dict(a,**b) 

A = {'a' :1,'b':2,'c':3}
B = {'h':55,'s':66,'d':88}
C = dict(A,**B)
print(C)



>>>{'a' :1,'b':2,'c':3,'h':55,'s':66,'d':88}

 

2) dict(a.items()+b.items()) 

A = {'a' :1,'b':2,'c':3}
B = {'h':55,'s':66,'d':88}
C = dict(A.items()+B.items())print(C)



>>>{'a' :1,'b':2,'c':3,'h':55,'s':66,'d':88}

3)c = {}  c.update(a)  c.update(b) 

A = {'a' :1,'b':2,'c':3}
B = {'h':55,'s':66,'d':88}
C = {}
C.update(A)
C.update(B)
print(C) >>>{'a' :1,'b':2,'c':3,'h':55,'s':66,'d':88}