如何检查嵌套列表中的组合?

时间:2018-06-09 21:16:12

标签: python

我制作了一个不错的游戏并且越过了游戏,我正在寻找一个组合是否有效。

我有一个获胜组合列表,例如[0,1,2]

我如何检查' X'这是所有三个,这是我到目前为止所得到的:

def draw_grid():
  print("-------------")
  print('|', grid[0], '|', grid[1], '|', grid[2], '|')
  print("-------------")
  print('|', grid[3], '|', grid[4], '|', grid[5], '|')
  print("-------------")
  print('|', grid[6], '|', grid[7], '|', grid[8], '|')
  print("-------------")

Symbol = 'X'

def Checker():
  Winning = [[0, 1, 2]]

  #statement to check...



global grid
grid = ['X', 'X', 'X', 3, 4, 5, 6, 7, 8]

draw_grid()
Checker()

3 个答案:

答案 0 :(得分:1)

你可以这样做:

def Checker(g,what):
    """Checks if any index combination inside Winner has all X"""
    Winning = [[0, 1, 2], [0,3,6], ] # you need to add all other 6 wind conditions here
    return any(  all( g[a]==what for a in x) for x in Winning)

win =  ['X', 'X', 'X', 3, 4, 5, 6, 7, 8]
win2 = ['X', 2, 3, 'X', 4, 5, 'X', 7, 8]
loose = ['X', 'X', 'o', 3, 4, 5, 6, 7, 8]

print (win, Checker(win,'X'))
print (win2, Checker(win2,'X'))
print (loose, Checker(loose,'X'))

输出:

['X', 'X', 'X', 3, 4, 5, 6, 7, 8] True
['X', 2, 3, 'X', 4, 5, 'X', 7, 8] True
['X', 'X', 'o', 3, 4, 5, 6, 7, 8] False
  • all()检查测试是否对可迭代的所有元素有效
  • any()检查迭代中的任何元素是否符合条件

了解any() / all()

的示例
t = [2,4,6]

print( all( x % 2 == 0 for x in t) )  # are all elements of t even?
print( any( x // 3 == 2 for x in t) ) # is any element of t divided by 3 == 2 ?
print( any( x % 2 == 1 for x in t) ) # is any element in t odd?

输出:

True
True
False

该行

return any(  all( g[a]==what for a in x) for x in Winning)

只需检查Winning任何元素([0,1,2][0,3,6] - 还有6个自己添加的条件)是否包含所有网格索引g[..](在此情况下给出),其值为what - 因此您可以检查XO - 任何一方都可能获胜。

答案 1 :(得分:1)

我不知道天气这是你想要的,但这里可能有用:

def draw_grid():
  print("-------------")
  print('|', grid[0], '|', grid[1], '|', grid[2], '|')
  print("-------------")
  print('|', grid[3], '|', grid[4], '|', grid[5], '|')
  print("-------------")
  print('|', grid[6], '|', grid[7], '|', grid[8], '|')
  print("-------------")

Symbol = 'X'

def Checker():
  Winning = [[0, 1, 2]]
  if grid[winning[0]] == Symbol and grid[winning[1]] == Symbol and grid[winning[2]] == Symbol:
      return "Match"



global grid
grid = ['X', 'X', 'X', 3, 4, 5, 6, 7, 8]

draw_grid()
Checker()

希望这会有所帮助。

答案 2 :(得分:0)

让我建议一个面向对象的解决方案。由于您要实现的是具有附加功能的嵌套列表,因此我们可以实现Grid类。

特别是,它的方法iter_winning_pos将返回所有合法获胜位置的生成器。然后,您可以选择自己喜欢的方式来查看if all elements in a list are identical

Grid class

class Grid():
    def __init__(self, n=3):
        self._grid = [[None] * n for _ in range(n)]

    def __getitem__(self, item):
        x, y = item
        return self._grid[x][y]

    def __setitem__(self, key, value):
        x, y = key
        self._grid[x][y] = value

    def __str__(self):
        s = ''
        for row in self._grid:
            s += '-' * (2 * len(self._grid) + 1) + '\n'
            s += ('|{}|\n'.format('|'.join([x if x is not None else ' ' for x in row])))
        s += '-' * (2 * len(self._grid) + 1) + '\n'
        return s

    def iter_winning_pos(self):
        for i in range(len(self._grid)):
            yield [(i, j) for j in range(len(self._grid))]
            yield [(j, i) for j in range(len(self._grid))]

        yield [(i, i) for i in range(len(self._grid))]
        yield [(i, len(self._grid) - 1 - i) for i in range(len(self._grid))]


    def is_winning(self):
        for line in self.iter_winning_pos():
            first = self[line[0]]
            if first is not None and all(self[x] == first for x in line):
                return first
        return None

实施例

g = Grid()
print('{} is winning'.format(g.is_winning()))

g[0, 0] = 'X'
g[1, 1] = 'O'
g[0, 1] = 'X'
g[0, 2] = 'X'

print(g)
print('{} is winning'.format(g.is_winning()))

输出

None is winning
-------
|X|X|X|
-------
| |O| |
-------
| | | |
-------

X is winning