I'm making a game where someone can select a square via notation and then perform an action on that square. Think chess, ie perform action on a2 or a3.
I need a2, for example, to be an array. How can I take a user's input and make it the name of the array?
I can basically make it work with:
if user_input == "a2":
a2 = ["value 1"]
elif user_input == "a3":
a3 = ["value 1"]
etc.
I'm thinking there has to be a better way. That's a lot of overhead and not easily scalable.
-mS
Use a dictionary:
h = {}
if user_input == "a2":
h["a2"] = ["value 1"]
elif user_input == "a3":
h["a3"] = ["value 1"]
Now, the good thing is that you can factorize your code:
h = {}
h[user_input] = ["value 1"]
Using a dict
, you'll be able to set keys at runtime:
board = dict()
square = user_input
board[square] = ["value 1"]
This will free you of the need to handle all squares one by one in the code, which is I think your question was about.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.