Python - 随机输出有一个结构

时间:2014-02-06 02:39:28

标签: python list random

我正在为python中的Tic Tac Toe游戏编写一个小脚本。我将Tic Tac Toe网格存储在这样的列表中(空网格示例):[[' ', ' ', ' ',], [' ', ' ', ' ',], [' ', ' ', ' ',]]。这些是列表的以下可能字符串:

  • ' '没有玩家标记此字段

  • 'X'玩家X

  • 'O'玩家O

我编写了一个创建空网格(create_grid)的函数,这是一个创建随机网格(create_random_grid)的函数(这将在以后用于测试)和打印的函数网格以这种方式使其可读取到最终用户(show_grid)。我在使用create_random_grid函数时遇到问题,但另外两种方法工作正常。以下是我接触create_random_grid函数的方法:

  • 首先使用create_grid

  • 创建一个空网格
  • 遍历网格线

  • 遍历

  • 行中的字符
  • 将字符更改为此处随机选择的项目。 ['X', 'O', ' ']

  • return网格

注意:我不希望预期输出的确切输出。对于实际输出,我并不总是如此,但所有行总是相同的。

enter image description here

我不知道为什么所有的线都是一样的。似乎最后生成的行是使用的行。我在我的代码中添加了一些调试行以及清楚显示我的问题的示例。我在我的代码中添加了一行,向我显示网格每个插槽的随机选择标记,但是我的输出与它不对应,除了它们匹配的最后一行。我在代码中包含了其他重要信息作为注释。粘贴链接here

CODE:

from random import choice

def create_grid(size=3):
    """
    size: int. The horizontal and vertical height of the grid. By default is set to 3 because thats normal
    returns: lst. A list of lines. lines is a list of strings
        Creates a empty playing field
    """
    x_lst = [' '] * size  # this is a horizontal line of the code
    lst = []  # final list
    for y in range(size):  # we append size times to the lst to get the proper height
        lst.append(x_lst)
    return lst

def show_grid(grid):
    """
    grid: list. A list of lines, where the lines are a list of string
    returns: None
    """
    for line in grid:
        print('[' + ']['.join(line)+']')  # print each symbol in a box

def create_random_grid(size=3):
    """
    size: int. The horizontal and vertical height of the grid. By default is set to 3 because thats normal
    returns: lst. A list of lines. lines is a list of strings
        Creates a grid with random player marks, used for testing purposes
    """
    grid = create_grid()
    symbols = ['X', 'O', ' ']
    for line in range(size):
        for column in range(size):
            # grid[line][column] = choice(symbols)  # what I want to use, but does not work

            # debug, the same version as ^^ but in its smaller steps
            random_item = choice(symbols)
            print 'line: ', line, 'column: ', column, 'symbol chosen: ', random_item  # shows randomly wirrten mark for each slot
            grid[line][column] = random_item  # over-write the indexes of grid with the randomly chosen symbol
    return grid

hardcoded_grid = [['X', ' ', 'X'], [' ', 'O', 'O'], ['O', 'X', ' ']]
grid = create_random_grid()
print('\nThe simple list view of the random grid:\n'), grid
print('\nThis grid was created using the create_random_grid method:\n')
show_grid(grid)
print('\nThis grid was hard coded (to show that the show_grid function works):\n')
show_grid(hardcoded_grid)

2 个答案:

答案 0 :(得分:2)

x_lst = [' '] * size
lst = []
for y in range(size):
    lst.append(x_lst)

lst的所有元素都是相同的列表对象。如果您想要相同但独立的列表,请每次创建一个新列表:

lst = []
for y in range(size):
    lst.append([' '] * size)

答案 1 :(得分:1)

您的电路板包含三个对单行的引用。您需要创建三个单独的行,如下所示:

lst = [[' ']*3 for _ in range(3)]