Python 列表理解 - 以 2+ 系列为条件

标签 python

我有两个系列(先前的和新的),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/

相关文章:

python - 找不到 flask 模板

python - 使用 beautiful soup 来模拟页面点击访问页面上的所有 HTML?

python - 使用 pandas 和 numpy 平均表索引

python - Hadoop streaming had中文乱码-files python

python - 为回归创建组标识符

python - 在 Keras 中向后传播?

python - lxml strip_tags 导致 AttributeError

python - 从另一个 Azure Function 调用 Azure Function

Python 套接字和请求

python - 如何使用 Python API 迭代 SQLite 数据库?