简体   繁体   中英

Python: Calling predefined variables/list/etc. from user input

Thanks for Your help in advance! I have the following problem in Python (I use Py 3.6.5):

  1. I have some lists, with some values in them. (I would like to use these values as predefined constants for the whole program.)

  2. In the main the program asks the user to name one of the lists. Eg. user writes: List1

  3. I would like to write a function which returns then the first element of List1. If the user writes List2, then the function should print the first element of List2, etc. (Not necessary, only if needed for the desired result)

I want the code to look something like this. I just wanted to indicate, that the user's input is stored in "Variable", which is then gived to the ListCall function.

List1 = [1,2,3]
List2 = [4,5,6]

def ListCall(List):
    #Some Code
    print(List[0])

# MAIN
Variable = input('Please choose a List: ')
ListCall(Variable)

Somehow I managed to achieve this desired result, with the following code:

List1 = [1,2,3]
List2 = [4,5,6]

Variable = vars()[(input('Please choose a List: '))]

print("First element of the choosen List is: ", Variable[0])

But I'm pretty sure, that this isn't the most elegant method and vars() maybe isn't intended for this kind of usage. I'm not even sticked to use an individual ListCall function, if it isn't needed... I just want it to work, with the most appropriate method.

You can store the list in a dict:

my_dict = {
              "List1": [1, 2, 3],
              "List2": [4, 5, 6]
          }
variable = input('Please choose a List: ')
try:
    print("First element of the choosen List is: ", my_dict[variable][0])
except KeyError:
    print("The list " + variable + "do not exist")

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM