0

I'm trying to use a list comprehension for two not nested for loops. This is my solution without 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))]

As you can see I want steps = [(10, 25), (13, 31), ...]

Is there an elegant and pythonic way to do it in one line with list comprehension or similar? In my mind I have something like this:

steps = [(int(x), int(j)) for x in np.linspace(10, 60, n_steps) and j in np.linspace(25, 150, n_steps)]
quamrana
  • 33,740
  • 12
  • 54
  • 68
Xbel
  • 647
  • 1
  • 10
  • 26
  • 1
    Does this answer your question? [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel). Assuming you are not aware of `zip`, a naive approach would be to collapse names: `steps = [(int(np.linspace(10, 60, n_steps)[i]), int(np.linspace(25, 150, n_steps)[i])) for i in range(len(np.linspace(10, 60, n_steps)))]` – Tomerikoo Jun 04 '20 at 09:03

2 Answers2

1

Using 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))]
paradocslover
  • 2,600
  • 3
  • 15
  • 38
1

Zip is your answer :)

list(zip(x_steps, y_steps))
ACimander
  • 1,691
  • 11
  • 16