python 基于索引重新排列嵌套列表

o7jaxewo  于 2023-01-19  发布在  Python
关注(0)|答案(2)|浏览(125)

假设我们有一个嵌套列表

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

我想创建一个新的嵌套列表,其中每个列表都基于索引进行组织

new_list = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

我想创建一个函数,将nested_list转换为new_list,但它很灵活,可以接受不同大小/长度的嵌套列表。
谢谢

mspsb9vt

mspsb9vt1#

nested_list = [[1, 2, 3], [1, 6, 2, 6], [0, 3, 7, 2, 6, 8, 2], [1, 3, 6, 2, 5]]

max_length = max([len(l) for l in nested_list])

new_list = [[l[i] for l in nested_list if i < len(l)] for i in range(max_length)]

print(new_list)
uurity8g

uurity8g2#

您可以通过以下方式实现您的结果:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

new_list = list(map(list, zip(*nested_list)))
#[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

或者你也可以使用列表解析:

new_list = [list(x) for x in zip(*nested_list)]
#[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

相关问题