【问题标题】:Loop over list of lists and use ith iterator循环列表列表并使用迭代器
【发布时间】:2017-09-22 14:53:54
【问题描述】:

所以我有以下列表:

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

我想遍历内部列表中的ith 元素。我可以使用zip

for x, y, z in zip(test[0], test[1], test[2]):
    print(x, y, z)

返回:

1 4 7
2 5 8
3 6 9

有没有一种更简洁、更 Pythonic 的方式来做到这一点? zip(test, axis=0) 之类的东西?

【问题讨论】:

  • for x, y, z in zip(*test):

标签: python list for-loop iterator zip


【解决方案1】:

您可以使用解包将输入的子列表作为变量参数传递给zip

for xyz in zip(*test):
    print(*xyz)

(您可以对 x,y,z 坐标执行相同操作,将参数传递给 print

【讨论】:

  • 这正是我想要的。谢谢!
【解决方案2】:

如果您使用numpy.array,您可以简单地使用数组的transpose 并遍历行

>>> import numpy as np
>>> test = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> t = np.array(test)
>>> t
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

然后迭代

for row in t.T:
    print(row)

[1 4 7]
[2 5 8]
[3 6 9]

根据您打算做什么,numpy 通常可能比列表推导更有效

【讨论】:

  • 主要问题更多是将各个值放入各自的变量中,而不是打印。不过谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-07-12
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多