![](/img/trans.png)
[英]I wondered if there is any way to make this line of code shorter: for x in letter
[英]Is there any way I can make this small piece of code shorter? (Python)
first = [0, 0, 0, 0]
second = [0, 0, 0, 0]
third = [0, 0, 0, 0]
fourth = [0, 0, 0, 0]
while 0 in first and 0 in second and 0 in third and 0 in fourth:
頂部的列表以每個值保持為0開頭。隨着程序的進行,我計划將列表中的值從0更改為其他數字。 有效地,我想知道是否有方法可以重寫'while'語句以檢查0是否在任何列表中,而沒有長鏈的'while not in __ and not in __'等。
while all(0 in i for i in [first,second,third,fourth]):
...
如果要檢查列表中是否包含0,請執行以下操作:
while any(0 in i for i in [first,second,third,fourth]):
...
您可以串聯/合並所有列表並檢查真實性:
while not all(first+second+third+fourth):
這將檢查任何False-y值,如果為0,則返回True。
while 0 in first + second + third + fourth:
# do stuff
您也可以map
ls = [first, second, third, fourth]
func = lambda x: 0 in x
while all(map(func, ls)):
#dostuff
如果您想讓0 in first and 0 in second and ...
話,請all
使用。 如果0 in first
0 in second
或0 in second
0 in first
請使用any
while not any(map(all, [first, second, ...])):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.