How to check if a number is in a list of lists?
所以我一直在检查数字0是否在另一个列表中的一组列表中有问题。这些行组成了一个帕克曼式游戏的迷宫,所以这是为了检查帕克曼是否吃了所有的硬币。
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | row1 =[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3] row2 =[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] row3 =[1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1] row4 =[1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1] row5 =[1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1] row6 =[1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1] row7 =[1,0,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,0,1] row8 =[1,0,0,0,0,1,0,1,1,1,1,1,0,1,0,0,0,0,1] row9 =[1,1,1,1,0,1,0,0,0,1,0,0,0,1,0,1,1,1,1] row10=[3,3,3,1,0,1,1,1,0,1,0,1,1,1,0,1,3,3,3] row11=[3,3,3,1,0,1,0,0,0,0,0,0,0,1,0,1,3,3,3] row12=[3,3,3,1,0,1,0,1,4,4,4,1,0,1,0,1,3,3,3] row13=[1,1,1,1,0,1,0,1,3,3,3,1,0,1,0,1,1,1,1] row14=[3,3,3,3,0,0,0,1,3,3,3,1,0,0,0,3,3,3,3] row15=[1,1,1,1,0,1,0,1,5,5,5,1,0,1,0,1,1,1,1] row16=[3,3,3,1,0,1,0,3,3,3,3,3,0,1,0,1,3,3,3] row17=[3,3,3,1,0,1,0,1,1,1,1,1,0,1,0,1,3,3,3] row18=[3,3,3,1,0,1,0,1,1,1,1,1,0,1,0,1,3,3,3] row19=[1,1,1,1,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1] row20=[1,0,0,0,0,1,1,1,0,1,0,1,1,1,0,0,0,0,1] row21=[1,0,1,1,0,0,0,0,0,3,0,0,0,0,0,1,1,0,1] row22=[1,0,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,0,1] row23=[1,2,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,2,1] row24=[1,0,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1] row25=[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] row26=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] maze = [row1,row2,row3,row4,row5,row6,row7,row8,row9,row10,row11,row12, row13,row14,row15,row16,row17,row18,row19,row20,row21,row22, row23,row24,row25,row26] |
所以我尝试过
任何帮助都将不胜感激,谢谢。
您必须遍历
1 2 | if not any(0 in i for i in maze): ... |
已经提到了
1 2 3 4 | from itertools import chain if 0 in chain.from_iterable(lst): # do something |
。
就像
第一次尝试后,您在顶级列表中只测试了
您必须遍历
1 2 3 4 5 6 | def has_zero(maze): for sublist in maze: for el in sublist: if el == 0: return True return False |
但是python为
Return True if any element of the iterable is true. If the iterable is empty, return False[...].
号
但是您还必须使用
1 | not any(el == 0 for sublist in maze for el in sublist) |
。
循环浏览子列表。也可使用
1 | if any(0 in sublist for sublist in maze) |
号
它将检查列表中是否有0
只要我了解您的问题,您可以使用以下代码:
1 2 3 4 5 6 7 8 | a = [1,1,1] b = [1,0,1] c = [0,1,2] d = [a,b,c] for i in d: if i.__contains__(0): print("yes") |