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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.