首页 > 代码库 > 合并dict、list的方法
合并dict、list的方法
dict1={1:[1,11,111],2:[2,22,222]}
dict2={3:[3,33,333],4:[4,44,444]}
合并两个字典得到类似
{1:[1,11,111],2:[2,22,222],3:[3,33,333],4:[4,44,444]}
方法1:
dictMerged1=dict(dict1.items()+dict2.items())
方法2:
dictMerged2=dict(dict1, **dict2)
方法2等同于:
dictMerged=dict1.copy()
dictMerged.update(dict2)
或者
dictMerged=dict(dict1)
dictMerged.update(dict2)
方法2比方法1速度快很多,用timeit测试如下
$ python -m timeit -s ‘dict1=dict2=dict((i,i) for i in range(100))‘ ‘dictMerged1=dict(dict1.items()+dict2.items())‘
10000 loops, best of 3: 20.7 usec per loop
$ python -m timeit -s ‘dict1=dict2=dict((i,i) for i in range(100))‘ ‘dictMerged2=dict(dict1,**dict2)‘
100000 loops, best of 3: 6.94 usec per loop
$ python -m timeit -s ‘dict1=dict2=dict((i,i) for i in range(100))‘ ‘dictMerged3=dict(dict1)‘ ‘dictMerged3.update(dict2)‘
100000 loops, best of 3: 7.09 usec per loop
$ python -m timeit -s ‘dict1=dict2=dict((i,i) for i in range(100))‘ ‘dictMerged4=dict1.copy()‘ ‘dictMerged4.update(dict2)‘
100000 loops, best of 3: 6.73 usec per loop
a = {‘a‘: 1}
b = {‘b‘: 2}
c = [1]
d = [‘a‘,2]
print(dict(a, **b))
print(c+d)
输出:
{‘a‘: 1, ‘b‘: 2}
[1, ‘a‘, 2]
除了直接相加(生成新的list),还有两种方法(修改其中一个list):
-
用list的extend方法,L1.extend(L2),该方法将参数L2的全部元素添加到L1的尾部,例如:
1
2
3
4
5
>>> L1
=
[
1
,
2
,
3
,
4
,
5
]
>>> L2
=
[
20
,
30
,
40
]
>>> L1.extend(L2)
>>> L1
[
1
,
2
,
3
,
4
,
5
,
20
,
30
,
40
]
-
用切片(slice)操作,L1[len(L1):len(L1)] = L2和上面的方法等价,例如:
1
2
3
4
5
6
>>> L1
=
[
1
,
2
,
3
,
4
,
5
]
>>> L2
=
[
20
,
30
,
40
]
>>> L1[
len
(L1):
len
(L1)]
=
L2
>>>
>>> L1
[
1
,
2
,
3
,
4
,
5
,
20
,
30
,
40
]
但切片方法用起来更灵活,可以插入到头部,或其他任意部位,例如:
加到开头:
1 2 3 4 5 |
>>> L1 = [ 1 , 2 , 3 , 4 , 5 ] >>> L2 = [ 20 , 30 , 40 ] >>> L1[ 0 : 0 ] = L2 >>> L1 [ 20 , 30 , 40 , 1 , 2 , 3 , 4 , 5 ]
|
-
加到中间:
1
2
3
4
5
6
|
>>> L1 = [ 1 , 2 , 3 , 4 , 5 ] >>> L2 = [ 20 , 30 , 40 ] >>> >>> L1[ 1 : 1 ] = L2 >>> L1 [ 1 , 20 , 30 , 40 , 2 , 3 , 4 , 5 ] |
去重合并两个list:
法一:
>>> a = [1,3,5,7]
>>> b = [1,3,4,6,8]
>>> c = list(set(a+b))
>>> a
[1, 3, 5, 7]
>>> b
[1, 3, 4, 6, 8]
>>> c
[1, 3, 4, 5, 6, 7, 8]
法二:
a
=
[
1
,
3
,
5
,
7
]
b
=
[
1
,
3
,
4
,
6
,
8
]
c
=
list
(
set
(a).union(
set
(b)))
a
=
[
1
,
3
,
5
,
7
]
b
=
[
1
,
3
,
4
,
6
,
8
]
c
=
list
(
set
(a) |
set
(b))
合并dict、list的方法