我试图将列表理解用于嵌套的循环太少。这是我没有列表理解的解决方案:
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的方法吗?在我心中,我有这样的东西:
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))]
邮政编码是您的答案:)
list(zip(x_steps, y_steps))