python - 将列表的列表拆分为每个列表的第一个元素的列表的命令

标签 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 循环?

最佳答案

您可以使用列表理解来提取每个 元组 的第 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,它会输出一个元组列表,每个元组代表一个元组索引:

results = list(zip(*L))

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

您甚至可以在此处使用序列拆包而不形成完整列表:

result1, result2 = zip(*L)

关于python - 将列表的列表拆分为每个列表的第一个元素的列表的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52865220/

相关文章:

java - 将集合和列表合并到 HashMap

java - Java中如何获取返回类型为List接口(interface)的对象?

python : Plot heatmap for large matrix

python - 属性错误 : 'module' object has no attribute 'exist'

python - 在 Atom 中导入含氢模块

Python SQLAlchemy ORM - 表反射*无*约束和索引反射

python - 绘制显示粒子百分比的等高线

python - 使用 scipy 对稀疏矩阵进行 groupby

python - Golang 可以像 Python 那样将字符串相乘吗?

java - 键入 DefaultListModel 以避免强制转换