【问题标题】:Python List Comprehension - Conditional on 2+ SeriesPython 列表理解 - 以 2+ 系列为条件
【发布时间】:2018-04-11 13:43:54
【问题描述】:

我有两个系列(以前的和新的),其中 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 行的列表。那么无论如何要使用这样的列表理解而不进入笛卡尔积?

【问题讨论】:

  • 举例说明输入的外观和输出应该是什么。此外,您的帖子存在严重的格式问题。
  • 也许你需要zip,但我很难理解这个问题。

标签: python


【解决方案1】:

我假设你想要这样的东西

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

【讨论】:

  • 感谢我所需要的!
  • @DarknessFalls 很高兴为您提供帮助。您可以通过清理 if-else 子句来改进您的代码。例如,看看这篇文章,其中条件存储在字典中:stackoverflow.com/a/10272927/8826944
【解决方案2】:

这应该可行:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-27
    • 2020-05-29
    • 2020-08-27
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    • 2020-01-07
    相关资源
    最近更新 更多