我有两个系列(先前的和新的),z 行的值都从 0 到 5,并且希望根据从旧列表切换到新列表的影响分配到存储桶中。对于此类操作,我通常使用 x in y 语句的列表理解,但现在我想同时将我的条件应用于两个变量。
我尝试使用下面的行:
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]
这会生成一个包含 z*z 行的列表,而我只想拥有一个包含 z 行的列表。那么无论如何要使用这样的列表理解而不进入笛卡尔积吗?
最佳答案
我想你想要这样的东西
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)]
关于Python 列表理解 - 以 2+ 系列为条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47017613/