独立循环的列表理解[重复]。

问题描述 投票:0回答:3

我试图使用列表理解来处理两个不嵌套的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)]
python list-comprehension
3个回答
1
投票

使用 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))]

1
投票

Zip是你的答案:)

list(zip(x_steps, y_steps))
© www.soinside.com 2019 - 2024. All rights reserved.