如何将列表合并到元组列表中?

什么是Pythonic方法来实现以下?

# Original lists: list_a = [1, 2, 3, 4] list_b = [5, 6, 7, 8] # List of tuples from 'list_a' and 'list_b': list_c = [(1,5), (2,6), (3,7), (4,8)] 

list_c每个成员都是一个元组,第一个成员来自list_a ,第二个来自list_b

 >>> list_a = [1, 2, 3, 4] >>> list_b = [5, 6, 7, 8] >>> zip(list_a, list_b) [(1, 5), (2, 6), (3, 7), (4, 8)] 

在python 3.0 zip中返回一个zip对象。 你可以通过调用list(zip(a, b))来得到一个列表。

你正在寻找内置函数zip 。

你可以使用地图lambda

 a = [2,3,4] b = [5,6,7] c = map(lambda x,y:(x,y),a,b) 

如果原始列表的长度不匹配,这也将起作用

我知道这是一个古老的问题,已经得到了答复,但由于某种原因,我仍然想发布这个替代解决方案。 我知道很容易找到哪个内置函数实现了你所需要的“魔法”,但是知道自己可以做到这一点并没有什么坏处。

 >>> list_1 = ['Ace', 'King'] >>> list_2 = ['Spades', 'Clubs', 'Diamonds'] >>> deck = [] >>> for i in range(max((len(list_1),len(list_2)))): while True: try: card = (list_1[i],list_2[i]) except IndexError: if len(list_1)>len(list_2): list_2.append('') card = (list_1[i],list_2[i]) elif len(list_1)<len(list_2): list_1.append('') card = (list_1[i], list_2[i]) continue deck.append(card) break >>> >>> #and the result should be: >>> print deck >>> [('Ace', 'Spades'), ('King', 'Clubs'), ('', 'Diamonds')] 

您在问题陈述中显示的输出不是元组,而是列表

 list_c = [(1,5), (2,6), (3,7), (4,8)] 

检查

 type(list_c) 

考虑到你想要的结果作为元组list_a和list_b,做

 tuple(zip(list_a,list_b))