Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
67 views
in Technique[技术] by (71.8m points)

python - How to use the value in a dictionary before actually running the command of the value

I am writing a code for tic-tac-toe and am a bit stuck! The user inputs a position and if the position inputed is empty (there is a number in its place) I would like to change the number to either X or O.

In my code below I have created a dictionary with a key representing the position on the board.

Can I call the content of the value of the key in my dictionary instead of the actual value; e.g. if the input is 0 I would like to use 'display_list[0][0]' instead of the value of display_list[0][0] which in this instance is 0.

row_1 = [0,1,2]
row_2 = [3,4,5]
row_3 = [6,7,8]
display_list = [row_1, row_2, row_3]

def valid_position():
    positions = {'0':display_list[0][0],
                 '1':display_list[0][1],
                 '2':display_list[0][2],
                 '3':display_list[1][0],
                 '4':display_list[1][1],
                 '5':display_list[1][2],
                 '6':display_list[2][0],
                 '7':display_list[2][1],
                 '8':display_list[2][2]
                }
    x = str(user_input())      # This is a user input from 0-8

    if x == str(positions[x]):
        display_list[..][..] = 'X'

Thanks

question from:https://stackoverflow.com/questions/65642414/how-to-use-the-value-in-a-dictionary-before-actually-running-the-command-of-the

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

if you want to go arround, you may add another dictionary to get the output you want like:

    positions_labels = {'0':'display_list[0][0]',
                 '1':'display_list[0][1]',
                 '2':'display_list[0][2]',
                 '3':'display_list[1][0]',
                 '4':'display_list[1][1]',
                 '5':'display_list[1][2]',
                 '6':'display_list[2][0]',
                 '7':'display_list[2][1]',
                 '8':'display_list[2][2]'
                }

so wherever you want the location use positions_labels[x]

Addition upon comment: If you want to evaluate the string content (get its value) you can do that as in the link

How to evaluate a math expression given in string form?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...