0

I have two series (prior & new) with z rows in both & values from 0 to 5 and would like to assign into buckets based on the impact from switching from the old to the new list. I normally use list comprehension for x in y statements for this type of operation, but now I would like to apply my condition on two variables at the same time.

I tried using the line below:

buckets = ['5) +10%' if x <= 1 and y == 3 else '4) +5%' if x == 2 and y == 3 else  \ 
'4) +5%' if x <= 1 and y == 2 else '2) -5%' if x == 3 and y == 2 else \
'1) -10%' if x == 3 and y <= 1 else '2) -5%' if x == 2 and y <= 1 else \
'3) 0%' for x in prior for y in new]   

This produces a list with z*z rows while I would like to only have a list with z rows. So anyway to use list comprehension like this without getting into a Cartesian product?

DarknessFalls
  • 111
  • 2
  • 5
  • 12
  • 2
    Give examples of how your inputs look and what your output should be. Also, there are serious formatting isssues with your post. – xssChauhan Oct 30 '17 at 14:24
  • 1
    Maybe you need `zip` but I have a hard time understanding the problem. – Andrey Oct 30 '17 at 14:25

2 Answers2

2

I assume you want something like this

 buckets = ['5) +10%' if x <= 1 and y == 3 else '4) +5%' if x == 2 and y == 3 else  \ 
'4) +5%' if x <= 1 and y == 2 else '2) -5%' if x == 3 and y == 2 else \
'1) -10%' if x == 3 and y <= 1 else '2) -5%' if x == 2 and y <= 1 else \
'3) 0%' for (x,y) in zip(prior, new)] 
Pulsar
  • 288
  • 1
  • 5
  • Thanks exactly what I needed! – DarknessFalls Oct 30 '17 at 14:51
  • @DarknessFalls Glad to help. You can improve your code by cleaning up the if-else clauses. For example, have a look at this post, where the conditions are stored in a dictionary: https://stackoverflow.com/a/10272927/8826944 – Pulsar Oct 30 '17 at 15:01
0

This should work:

buckets = ['5) +10%' if x[i] <= 1 and y[i] == 3 else '4) +5%' if x[i] == 2 and y[i] == 3 else  \ 
'4) +5%' if x[i] <= 1 and y[i] == 2 else '2) -5%' if x[i] == 3 and y[i] == 2 else \
'1) -10%' if x[i] == 3 and y[i] <= 1 else '2) -5%' if x[i] == 2 and y[i] <= 1 else \
'3) 0%' for i in range(len(prior))] 
Ankur Ankan
  • 2,953
  • 2
  • 23
  • 38