【问题标题】:Given a list of lists, how can i create another specific kind of list给定一个列表列表,我如何创建另一种特定类型的列表
【发布时间】:2022-01-06 15:08:49
【问题描述】:

所以我真正想做的是从另一个列表列表中创建一个列表列表,但是这个新列表会占用原始列表中每个列表的位置并创建一个新列表。

例如。

[[5,6,3],[2,0,4],[3,8,5]]

会变成

[[5,2,3],[6,0,8],[3,4,5]]

所以新列表是旧列表的第 0 位和第 1 位,依此类推。

【问题讨论】:

  • 对角翻转列表,最常用的成语是list(zip(*your_list))
  • 我刚试过这个,但它只是给了我已经拥有的列表

标签: python-3.x list loops


【解决方案1】:

您可以制作单独的列表,然后将它们组合成新列表。

list = [[5,6,3],[2,0,4],[3,8,5]]

new_list_0 = [list[i][0] for i in range(0, len(list))]
new_list_1 = [list[i][1] for i in range(0, len(list))]
new_list_2 = [list[i][2] for i in range(0, len(list))]

new_list = []

new_list.append(new_list_0)
new_list.append(new_list_1)
new_list.append(new_list_2)

print(new_list)

但是添加新列表会很麻烦。

list(zip(*list)) 给出元组列表

list_of_numbers = [[5,6,3],[2,0,4],[3,8,5]]

new_list_of_numbers = list(zip(list_of_numbers[0], list_of_numbers[1], list_of_numbers[2]))
print(new_list_of_numbers)

输出:

[(5, 2, 3), (6, 0, 8), (3, 4, 5)]

【讨论】:

  • 如果我想让它成为一个函数,只是一个简单的问题,因为原始 listoflist 大小可能会有所不同,我该怎么做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多