我试图使用列表理解来处理两个不嵌套的for循环。这是我的解决方案,没有使用list comprehension。
import numpy as np
n_steps = 20
x_steps = [int(i) for i in np.linspace(10, 60, n_steps)]
y_steps = [int(i) for i in np.linspace(25, 150, n_steps)]
steps = [(x_steps[i], y_steps[i]) for i in range(len(x_steps))]
如你所见,我想 steps = [(10, 25), (13, 31), ...]
有没有一种优雅的、pythonic的方法可以用list comprehension或类似的方法在一行中完成?在我的脑海中,我有这样的东西。
steps = [(int(x), int(j)) for x in np.linspace(10, 60, n_steps) and j in np.linspace(25, 150, n_steps)]
使用 zip
import numpy as np
n_steps = 20
steps = [(int(i),int(j)) for i,j in zip(np.linspace(10, 60, n_steps),np.linspace(25, 150, n_steps))]
Zip是你的答案:)
list(zip(x_steps, y_steps))