【问题标题】:If/else in python list comprehensionpython列表理解中的if/else
【发布时间】:2018-11-10 22:46:34
【问题描述】:

我想根据传递的参数从文件中返回随机单词。但如果参数不匹配任何我不想返回任何东西。我的方法如下:

def word_from_score(self,score):
    print(random.choices([word for word in self.file if sum([LETTER_SCORES[letter] for letter in word ]) == score]))

它根据命令行中传递的参数从文件中返回正确的单词,但如果参数不匹配,我不想返回任何内容,例如''。我怎么能在这个语句中添加其他内容?

【问题讨论】:

标签: python list-comprehension


【解决方案1】:

应该是:

def word_from_score(self,score):
    print(random.choices([(word if sum([LETTER_SCORES[letter] for letter in word ]) == score else "") for word in self.file]))

(... if ... else ...) 实际上是三元运算符,而不是周围列表理解的一部分。

【讨论】:

  • 编辑:它不起作用,atm 它返回“即使在文件中是单词,其中字母的总和在参数中传递
  • @Frendom (1) 您是否检查过它是否适用于您的原始功能? (2) 能否举个简单的例子进行测试?
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
  • 2018-04-27
  • 2017-04-26
  • 2020-08-27
  • 2020-01-07
  • 1970-01-01
相关资源
最近更新 更多