列出子列表中的第一个、第二个、第三个...元素

时间:2021-07-12 17:48:14

标签: python list

如何将每个子列表中的第一个、第二个、第三个等元素一起列出?

> main_list = [[2,3,10],[5,8,1]]

预期的答案应该是:

> new_list = [[2,5],[3,8],[10,1]]
> #The first sub list from new_list [2,5] contains the first elements from the sub lists in main_list
> #The second sub list from new_list [3,8] contains the second elements from the sub lists in main_list
> #This pattern continues for all elements in main_list

我需要一个不需要使用 numpy 或 groupby 的简单代码。

到目前为止,我的代码只列出了 main_list 中每个子列表的第一个元素。

> new_list = [item[0] for item in main_list]
> # this gives answer of [2,5]

2 个答案:

答案 0 :(得分:1)

您可以使用itertools.zip_longest,例如以下代码:

from itertools import zip_longest

main_list = [[2,3,10],[5,8,1]]

print(list(zip_longest(*main_list)))

产生结果[(2, 5), (3, 8), (10, 1)]

答案 1 :(得分:1)

您可以将列表理解与列表解包一起使用,并且 zip

>>> [[*items] for items in zip(*main_list)]
[[2, 5], [3, 8], [10, 1]]
  • zip(*main_list) 将解包 main_list 并创建 zip 对象,让您并行迭代每个内部列表,而 [*items] 将解包来自迭代 {{1} 的元组并将创建列表。
相关问题