假设我们有一个嵌套列表
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,但它很灵活,可以接受不同大小/长度的嵌套列表。谢谢
nested_list
new_list
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)
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]]
2条答案
按热度按时间mspsb9vt1#
uurity8g2#
您可以通过以下方式实现您的结果:
或者你也可以使用列表解析: