在python中向列表添加值

时间:2015-07-02 13:24:40

标签: python

我在python上创建了一个简单的8 * 8网格,并希望能够在左下角为它绘制1“X”,并在代码中管理10个随机“T”,我已在代码中管理下面。问题是当我然后尝试再向网格中添加另外5个随机“B”时,它有时只会调出4,因为它在列表中迭代并且没有看到“ - ”它正在计算为迭代,当它达到5时,它就会停止。

from random import randint
board =[]
for item in range (0,8):
    board.append(["-"]*8)

def print_board (board):
    for row in board:
        print ("  ".join(row))

treasure = 10
bandits = 5

def player1(board):
    board[7][0] = 'X'

def random_treasure (board,x):
    for n in range(x):
    treasure_location1 = randint(0, len(board)-1)
    treasure_location2 = randint(0, len(board)-1)
    board[treasure_location1][treasure_location2]

        while board[treasure_location1][treasure_location2] == "X" or board[treasure_location1][treasure_location2] == "T":
        treasure_location1 = randint(0, len(board)-1)
        else:
            board[treasure_location1][treasure_location2] = 'T'

def random_bandits (board,y):
    for n in range(y):
        global treasure_location1
        global treasure_location2
        bandit_location1 = randint(0, len(board)-1)
        bandit_location2 = randint(0, len(board)-1)
        board[bandit_location1][bandit_location2]

        while board[bandit_location1][bandit_location2] == "X" or board[bandit_location1][bandit_location2] == "T":
        bandit_location1 = randint(0, len(board)-1)
        else:
            board[bandit_location1][bandit_location2] = "B"


player1(board)
random_treasure(board,treasure)
random_bandits (board,bandits)

print_board(board)

我认为做这样的事情会更有效率,因此如果它看到“ - ”只会打印一个T或B到板上,但它只打印一个T而不是我想要的范围。我知道这可能是一些简单的逻辑错误,但我有点卡住,所以感谢任何帮助,谢谢

def random_treasure (board,x):
    treasure_location1 = randint(0, len(board)-1)
    treasure_location2 = randint(0, len(board)-1)
    board[treasure_location1][treasure_location2]

    while board[treasure_location1][treasure_location2] == "-":
        for n in range(x):
            board.append("T")

1 个答案:

答案 0 :(得分:0)

尝试使用递归,因此将变量设置为5,每次成功时将变量减少一个,否则传递然后在变量大于零时放入while循环调用函数