![](/img/trans.png)
[英]Using list comprehension instead of for loop when working with Django QuerySets
[英]List Comprehension instead of a for loop not working
Udemy 課程:遍歷密碼列表的項目,如果項目中包含字符串“ba”或“ab”,則在每次迭代中打印出該項目。
密碼 = ['ccavfb', 'baaded', 'bbaa', 'aaeed', 'vbb', 'aadeba', 'aba', 'dee', 'dade', 'abc', 'aae', 'dded' , 'abb', 'aaf', 'ffaec']
我知道我可以為此創建以下 for 循環並且它會起作用
for x in passwords:
if 'ab' in x or 'ba' in x:
print(x)
但我剛剛了解了列表理解,所以我嘗試在循環中制作以下 function 到 go。
def checker(passes):
return (x for x in passes if 'ab' in x or 'ba' in x)
print(checker(passwords))
然而,這不起作用並給我這個錯誤:<generator object checker.. at 0x00000212414B4110> 即使在我的老朋友谷歌尋求幫助之后,我也不知道這意味着什么。 \我不明白為什么這個 function 不工作請幫我解釋我錯過了什么。 我完全迷路了。
這是根據答案提示的預期結果
baaded
bbaa
aadeba
aba
abc
abb
即使那確實有效,它也不會給你想要的結果。 如果你想使用那種風格,你將不得不join
它。
def checker(passes):
return '\n'.join(x for x in passes if 'ab' in x or 'ba' in x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.