python - 有没有一种方法可以使用列表理解来根据提取的子列表公共索引创建列表?

python - is there a way to use list comprehension to create a list based on the extracted common indexes of sublists?

我想找出一种干净的方法来获取每个子列表的相同索引处的元素,并根据这些提取的元素创建一个新列表,所以首先我想要一个包含每个较早子列表的元素 0 的子列表,然后元素 1、2 等相同。目前我正在使用以下代码来获得我想要的结果:

lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
approach_1 = []

for i, item in enumerate(lst[0]):
    approach_1.append([item, lst[1][i], lst[2][i], lst[3][i]])

这给了我

approach_1 = [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]

我正在寻找结果,但有没有办法让我在一行中实现这一目标?我可以对一个元素使用以下内容:

approach_2 = [x[0] for x in lst] 

是否有与此类似的东西 return 与 approach_1 相同的结果?

内置的 zip 函数完全可以满足您的需求:

>>> lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
>>> list(zip(*lst))
[(1, 'a', True, 14.5), (2, 'b', True, 15.6), (3, 'c', False, 12.5), (4, 'd', True, 12.3)]

一行可以写两个for循环!

new_list = [[j[i] for j in lst] for i in range(0, len(lst[0]))]

列表理解的解决方案:

[list(i) for i in zip(*lst)]

# [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]

或者,使用地图

list(map(list, zip(*lst)))

会给你同样的结果

list( zip( lst[0], lst[1], lst[2], lst[3] ) )

或者如果你希望每个元素都是一个列表而不是一个元组,你可以这样做

result = [ list(x) for x in list( zip( lst[0], lst[1], lst[2], lst[3] ) ) ]