python列表理解中的if/else [英] If/else in python list comprehension
本文介绍了python列表理解中的if/else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据传递的参数从文件中返回随机单词.但是,如果参数与任何内容都不匹配,我就不希望返回任何内容.我的方法如下:
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?
推荐答案
应为:
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 ...)
实际上是三元运算符,不是周围列表理解的一部分.
The (... if ... else ...)
is actually the ternary operator and not part of the surrounding list comprehension.
这篇关于python列表理解中的if/else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文