我的问题是,我正在检查一个可能获胜的列表(里面有每个组合的列表),并且我有这个列表,它检查胜利列表中的第一个列表,以及其中的所有元素。我怎样才能让这个if语句检查所有的元素?例如,0表示胜利列表中的所有不同列表,并检查它们。
在胜利中的x:
if 'x' in wins[0] and wins[0][0] and wins[0][1] and wins[0][2] and wins[0][3] == 'x':
print("\nWell done! You've won!")
menu(发布于 2013-11-28 12:14:23
这将检查每个子列表== x中的所有项。
wins = [['x', 'x', 0, 'x'], ['x', 0, 0, 'x'], ['x', 'x', 'x', 'x']]
# Iterate over all sublists
for win in wins:
# Iterate over all elements in list, and check if all equals x
if all(i == 'x' for i in win):
# If this is the case - write a message and break out of the loop
print("Well done! You've won!")
break如果你想按你自己的方式去做,你必须修复你的原始代码中的一些问题。你不能说if a and b and c and d == 'x'。Python像这样交织在一起:
if a is not False and
b is not False and
c is not False and
d == 'x'您希望检查每个单独的项目,例如:
if wins[0][0] == 'x' and wins[0][1] == 'x' and wins[0][2] == 'x' and wins[0][3] == 'x': 然后把所有这些放在一个循环中:
for sublist in wins:
if sublist[0] == 'x' and sublist[1] == 'x' and sublist[2] == 'x' and sublist[3] == 'x':
print("Well done! You've won!")
break但是这真的很麻烦--你应该用循环代替。这是一个可能更清楚的例子:
for sublist in wins:
for item in sublist:
if item != 'x'
break
else:
print("Well done! You've won!")
break此代码将遍历所有子列表,然后循环遍历子列表中的所有项。如果遇到一个不等于“x”的项,内部循环就会中断。
在内部for循环的末尾,有一个end子句。在Python中很少使用这一特性,但是拥有它确实很好。只有在循环未中断时才执行else子句中的代码。
在我们的例子中,这意味着所有的项都等于'x‘。
https://stackoverflow.com/questions/20265775
复制相似问题