Function with arguments in two lists

2019-03-22 14:25发布

问题:

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)?

回答1:

zip is what you want:

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


回答2:

You need to use zip:

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


回答3:

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.



回答4:

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.