用于将列表列表拆分为每个列表的第一个元素的列表的命令

时间:2018-10-18 00:09:44

标签: python python-3.x list

我试图从列表列表中创建2个列表,下面的代码是一个简单易用的示例,但是认为有一个命令可以代替创建for循环进行拆分是有意义的。

def add_five(x):
    return x,x + 5
result1=[]
result2=[]
nums = [11, 22, 33, 44, 55]
result = list(map(add_five, nums))
print(result)
for n in range(len(result)):
    result1.append(result[n][0])
    result2.append(result[n][1])
print(result1,result2)

列表列表为:

[(11, 16), (22, 27), (33, 38), (44, 49), (55, 60)]
result1=[11, 22, 33, 44, 55] 
result2=[16, 27, 38, 49, 60]

有没有可以使用for循环帮助的命令?

1 个答案:

答案 0 :(得分:1)

您可以使用列表推导来提取每个tuple n 个元素:

L = [(11, 16), (22, 27), (33, 38), (44, 49), (55, 60)]

result1 = [i[0] for i in L]
result2 = [i[1] for i in L]

功能上,您可以将operator.itemgetter用作等效项:

from operator import itemgetter

result1 = list(map(itemgetter(0), L))
result2 = list(map(itemgetter(1), L))

如果您不知道元组的大小,建议的解决方案是zip,它将输出一个元组列表,每个元组代表一个元组索引:< / p>

results = list(zip(*L))

[(11, 22, 33, 44, 55), (16, 27, 38, 49, 60)]

您甚至可以在此处使用序列解压缩而无需形成完整列表:

result1, result2 = zip(*L)
相关问题