如何返回值名称(有效,无效)而不是返回1和0

时间:2019-05-02 18:01:57

标签: python

我已经使该函数返回了生命游戏中死活的细胞。与其返回0代表死亡,返回1代表存活,不如返回活着的死亡

这是我目前可以运行的示例: **

0 0 1 0 1 1
0 0 0 0 0 1
0 0 0 0 1 1
1 1 0 1 1 1
0 0 1 1 0 1
0 0 1 1 1 0

**

def update_game_board(input_board):

    alive = 1
    dead = 0
    row = 0

    ##Loops through 
    for row in range(0,input_board.shape[0]):
        print("**")
        for index in range(0,input_board.shape[1]):
            print(input_board[row][index])
            index = index + 1

    return np.logical_not(input_board)*1

4 个答案:

答案 0 :(得分:1)

使用字典:

value = {0: 'Dead', 1: 'Alive'}
def update_game_board(input_board):

    alive = 1
    dead = 0
    row = 0

    ##Loops through 
    for row in range(0,input_board.shape[0]):
        print("**")
        for index in range(0,input_board.shape[1]):
            print(input_board[row][index])
            index = index + 1

    return value[np.logical_not(input_board)*1]

答案 1 :(得分:1)

使用将整数值映射到所需字符串的字典吗?

output = {1: "alive", 0: "dead"}

...

    print(output[input_board[row][index]])

答案 2 :(得分:0)

首先,使用l = ['dead', 'alive']列出列表。然后,在最后一行,使用return np.logical_not(input_board)*1而不是使用return l[np.logical_not(input_board)*1]

答案 3 :(得分:0)

您尚未列出您的主程序,因此我们不确定您如何实现董事会。我设计这个是为了解决我认为将所有内容链接在一起的问题。这仅仅是在主程序中从0/1到“ dead”,“ alive”(每个5个字符的一致性)的转换;功能逻辑是您自己玩的。

board = np.array([
    [0, 0, 1, 0, 1, 1],
    [0, 0, 0, 0, 0, 1],
    [0, 0, 0, 0, 1, 1],
    [1, 1, 0, 1, 1, 1],
    [0, 0, 1, 1, 0, 1],
    [0, 0, 1, 1, 1, 0]
])

# Make a conversion table.
# Instantiate it as a lambda function,
#   and vectorize that to support arrays.
life_status = {0: "dead ", 1:"alive"}
life_text = lambda c: life_status[c]
vect_life = np.vectorize(life_text)

print("\nGENERATION 0:")
print(vect_life(board))

next_gen = update_game_board(board)
print("\nGENERATION 1:")
print(vect_life(next_gen))

输出:

GENERATION 0:
[['dead ' 'dead ' 'alive' 'dead ' 'alive' 'alive']
 ['dead ' 'dead ' 'dead ' 'dead ' 'dead ' 'alive']
 ['dead ' 'dead ' 'dead ' 'dead ' 'alive' 'alive']
 ['alive' 'alive' 'dead ' 'alive' 'alive' 'alive']
 ['dead ' 'dead ' 'alive' 'alive' 'dead ' 'alive']
 ['dead ' 'dead ' 'alive' 'alive' 'alive' 'dead ']]

GENERATION 1:
[['alive' 'alive' 'dead ' 'alive' 'dead ' 'dead ']
 ['alive' 'alive' 'alive' 'alive' 'alive' 'dead ']
 ['alive' 'alive' 'alive' 'alive' 'dead ' 'dead ']
 ['dead ' 'dead ' 'alive' 'dead ' 'dead ' 'dead ']
 ['alive' 'alive' 'dead ' 'dead ' 'alive' 'dead ']
 ['alive' 'alive' 'dead ' 'dead ' 'dead ' 'alive']]

这些结果有些反白,因为您的update仅否定了每个单元格,但是我相信当您跳过这一部分时,您会适当地使其复杂化。 :-)