30

I have two lists xscat and yscat. I would like the list comprehension to pick up x and y in xscat and yscat respectively. Resulting list should contain peaks([x[0], y[0]]), peaks([x[1], y[1]]) , etc

xscat=yscat=[-1, -1.5,5]
[peaks([x,y]) for x,y in xscat,yscat]

Can you find any solution using comprehensions ? or other ways to put it (map)?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
kiriloff
  • 25,609
  • 37
  • 148
  • 229

4 Answers4

44

zip is what you want:

[peaks([x,y]) for x,y in zip(xscat,yscat)]
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
11

You need to use zip:

[peaks([x,y]) for (x,y) in zip(xscat, yscat)]
Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
8

I assume from your example that you want to use zip() but, just in case what you really want to do is iterate over ALL possible combinations of xscat and yscat then you have more work to do...

So, if you want (xscat[0],yscat[0]), (xscat[0], yscat[1]), (xscat[0], yscat[2]), etc... you can first do a nested comprehension:

((x,y) for x in xscat for y in yscat)

will generate ALL the pairs and

[peaks(x,y) for x in xscat for y in yscat]

should yield the solution if you want all permutations.

Also, take care with zip/map - you will get different results from those if the lists (xscat and yscat) are not of the same lenght - make sure to pick the one that yields that solution you need.

tom stratton
  • 668
  • 7
  • 13
3

Try zip: http://docs.python.org/library/functions.html#zip

[peaks(x) for x in zip(zscat, yscat)]

Edit

This assumes the peaks can accept a tuple.

grieve
  • 13,220
  • 10
  • 49
  • 61