简体   繁体   English

如果/else在python列表理解中

[英]If/else in python list comprehension

I would like to return random word from file, based on passed argument.我想根据传递的参数从文件中返回随机单词。 But if the argument doesn't match anythning I dont want to return anything.但是如果参数不匹配任何东西,我不想返回任何东西。 My method looks like:我的方法看起来像:

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

It returns the correct word from file based on passed argument in command line, but if the argument doesnt match, i want to return nothing, like ''.它根据命令行中传递的参数从文件中返回正确的单词,但如果参数不匹配,我不想返回任何内容,例如''。 How could I add else to this statement?我如何在此声明中添加其他内容?

Should be:应该:

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

The (... if ... else ...) is actually the ternary operator and not part of the surrounding list comprehension. (... if ... else ...)实际上是三元运算符,而不是周围列表推导式的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM