检查列表从输入添加到python 3中的字符串

时间:2017-06-12 19:10:32

标签: python python-3.5

你好堆栈溢出社区,我正在研究Python 3中的国际象棋移动预测器并且偶然发现了一个障碍,问题是我正在尝试根据输入检查一个正方形的可能移动列表。然而,要表明此举是针对黑色还是白色,我必须在它之后说出一个w。如何检查列表由字符串和输入组成的名称? 这是第一步的可能动作列表:

    PWA2m = ["A3", "A4", "B3"]
    PWB2m = ["B3", "B4", "C3", "A3"]
    PWC2m = ["C3", "C4", "D3", "B3"]
    PWD2m = ["D3", "D4", "E3", "C3"]
    PWE2m = ["E3", "E4", "D3", "F3"]
    PWF2m = ["F3", "F4", "E3", "G3"]
    PWG2m = ["G3", "G4", "F3", "H3"]
    PWH2m = ["H3", "H4", "G3"]
    K1WB1m = ["A3", "C3"]
    K2WG1m = ["F3", "H3"]

到目前为止这是检查器:

     wmove = input("What square are you moving from?")
     if wmove == "":
       Piece = squares.get(wmove)

如果用户放入有效的方块,我希望输出类似的内容:

    Possible Moves for PawnWhite:
    B3, B4, C3, A3

1 个答案:

答案 0 :(得分:0)

听起来你正试图通过搜索列表的名称来访问不同部分的列表。但是,程序通常不应访问变量的名称。解决问题的一个简单方法是使用dict来存储各个部分及其可能性列表:

current_state = {"A1":"Kw", "B5":"Qb"} # and so on
current_possibilities = {"A1": ["B2", "A2"], "B5":["B4", "B6", "C4", "C5", "C6"]}

然后,您可以非常简单地访问当前的位置/移动位置:

print("The piece at {} is a {} and can move to: {}".format(
    input, current_state[input][:-1], current_possibilities[input]))

根据上面的输入"A1",将打印:

The piece at A1 is a K and can move to: ['B4', 'B6', 'C4', 'C5', 'C6']