# Python按照元素顺序合并list

1 篇文章 0 订阅

### 一、普通list合并

    list1 = ["v1-1", "v1-2", "v1-3"]
list2 = ["v2-1", "v2-2", "v2-3"]
list3 = ["v3-1", "v3-2"]
tmp = list1 + list2 + list3
print(tmp)


[‘v1-1’, ‘v1-2’, ‘v1-3’, ‘v2-1’, ‘v2-2’, ‘v2-3’, ‘v3-1’, ‘v3-2’]

### 二、按照元素顺序合并

1. 等长list合并

[‘v1-1’, ‘v2-1’, ‘v1-2’, ‘v2-2’, ‘v1-3’, ‘v2-3’]

    tmp = list(zip(list1, list2))
print(tmp)
merge1 = [t for v in tmp for t in v]
print(merge1)


[(‘v1-1’, ‘v2-1’), (‘v1-2’, ‘v2-2’), (‘v1-3’, ‘v2-3’)]
[‘v1-1’, ‘v2-1’, ‘v1-2’, ‘v2-2’, ‘v1-3’, ‘v2-3’]

zip() 会先将list按照元素顺序变成tuple list，然后再将tuple list转成list就可以了

    tmp = list(zip(list1, list2, list3))
print(tmp)
merge1 = [t for v in tmp for t in v]
print(merge1)


[(‘v1-1’, ‘v2-1’, ‘v3-1’), (‘v1-2’, ‘v2-2’, ‘v3-2’)]
[‘v1-1’, ‘v2-1’, ‘v3-1’, ‘v1-2’, ‘v2-2’, ‘v3-2’]

1. 不等长list合并
也就是：

[‘v1-1’, ‘v2-1’, ‘v3-1’, ‘v1-2’, ‘v2-2’, 'v3-2, ‘v1-3’, ‘v2-3’]

    tmp = list(itertools.zip_longest(list1, list3))
print(tmp)
merge1 = [t for v in tmp for t in v if t is not None]
print(merge1)


[(‘v1-1’, ‘v3-1’), (‘v1-2’, ‘v3-2’), (‘v1-3’, None)]
[‘v1-1’, ‘v3-1’, ‘v1-2’, ‘v3-2’, ‘v1-3’]

1. 合并dictionary的list值
    dict = {"key1": ["v1-1", "v1-2", "v1-3"], "key2": ["v2-1", "v2-2", "v2-3"], "key3": ["v3-1", "v3-2"]}
tmp = list(itertools.zip_longest(*dict.values()))
print(tmp)
tmp = list(zip(*dict.values()))
print(tmp)


[(‘v1-1’, ‘v2-1’, ‘v3-1’), (‘v1-2’, ‘v2-2’, ‘v3-2’), (‘v1-3’, ‘v2-3’, None)]
[(‘v1-1’, ‘v2-1’, ‘v3-1’), (‘v1-2’, ‘v2-2’, ‘v3-2’)]

    tmp = list(zip(list1, list2))
print(tmp)
merge1 = [t for v in tmp for t in v]
print(merge1)
merge2 = list(sum(tmp, ()))
print(merge2)
merge3 = list(itertools.chain(*tmp))
print(merge3)

tmp = list(itertools.zip_longest(list1, list2, list3))
print(tmp)
merge1 = [t for v in tmp for t in v if t is not None]
print(merge1)
merge2 = [v for v in sum(tmp, ()) if v is not None]
print(merge2)
merge3 = [v for v in itertools.chain(*tmp) if v is not None]
print(merge3)


[(‘v1-1’, ‘v2-1’), (‘v1-2’, ‘v2-2’), (‘v1-3’, ‘v2-3’)]
[‘v1-1’, ‘v2-1’, ‘v1-2’, ‘v2-2’, ‘v1-3’, ‘v2-3’]
[‘v1-1’, ‘v2-1’, ‘v1-2’, ‘v2-2’, ‘v1-3’, ‘v2-3’]
[‘v1-1’, ‘v2-1’, ‘v1-2’, ‘v2-2’, ‘v1-3’, ‘v2-3’]
[(‘v1-1’, ‘v2-1’, ‘v3-1’), (‘v1-2’, ‘v2-2’, ‘v3-2’), (‘v1-3’, ‘v2-3’, None)]
[‘v1-1’, ‘v2-1’, ‘v3-1’, ‘v1-2’, ‘v2-2’, ‘v3-2’, ‘v1-3’, ‘v2-3’]
[‘v1-1’, ‘v2-1’, ‘v3-1’, ‘v1-2’, ‘v2-2’, ‘v3-2’, ‘v1-3’, ‘v2-3’]
[‘v1-1’, ‘v2-1’, ‘v3-1’, ‘v1-2’, ‘v2-2’, ‘v3-2’, ‘v1-3’, ‘v2-3’]

• 5
点赞
• 16
收藏
觉得还不错? 一键收藏
• 0
评论
01-29 1154
06-24 4467
05-11 4202
03-02 9131
09-29 4705
08-27 1008
01-05 1847
11-21 3841
03-10 1412

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。