嗨,可以在我的for
列表上运行Matrix
循环吗?
我尝试了Matrix [o + for i in range 4]
,但没有成功。
for i in range(col):
for o in range(row):
if Matrix[o][i] == "X" and Matrix[o + for i in range 4][i] == "X":
return True
答案 0 :(得分:0)
Matrix[o + for i in range 4]
是荒谬的。如果您的目标是检查给定的“列”中至少有五个符号等于X
,则解决方案是对它们进行计数并进行比较:
for i in range(col):
# booleans have numeric value of 1/0 for True/False, so sum works on them
if sum(r[i] == 'X' for r in Matrix) >= 5:
return True
如果连续必须有五个这样的符号,则代码会稍微复杂一些(因为迭代list
的片段很烦人):
for i in range(col):
for o in range(row):
rows = Matrix[o:o+5] # Slice out five consecutive rows
# Check if given column in all five is X
if all(r[i] == 'X' for r in rows):
return True
这有点低效(因为即使我们可以肯定地知道不会发生这种运行,它也会一次重复地切片并重新检查五个元素),但是除非代码处于热循环中并且绝对对性能至关重要。在不使事情复杂化的情况下提高性能的唯一方法是,确保矩阵在每个单元格中仅包含一个字符,在这种情况下,代码可以简化为:
for i in range(col):
# Get characters from each cell in column, join to single string
colstr = ''.join([r[i] for r in Matrix])
if 'XXXXX' in colstr: # Scan string once (pushes all work to C, should be fast)
return True