如何在Python中逐个加入列表? [英] How to join lists element-wise in Python?

查看:306
本文介绍了如何在Python中逐个加入列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

l1 = [4, 6, 8]
l2 = [a, b, c]

结果= [(4,a),(6,b),(8,c)]

我该怎么做?

推荐答案

使用 .

l1 = [1, 2, 3]
l2 = [4, 5, 6]
>>> zip(l1, l2)
[(1, 4), (2, 5), (3, 6)]

请注意,如果列表的长度不同,结果将被截断为最短输入的长度.

Note that if your lists are of different lengths, the result will be truncated to the length of the shortest input.

>>> print zip([1, 2, 3],[4, 5, 6, 7])
[(1, 4), (2, 5), (3, 6)]

您还可以将zip与两个以上的列表一起使用:

You can also use zip with more than two lists:

>>> zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

如果有列表列表,则可以使用星号致电zip:

If you have a list of lists, you can call zip using an asterisk:

>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*l)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

这篇关于如何在Python中逐个加入列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆