简体   繁体   中英

How do I print a list choosen by the user via input?

I have two lists defined in a python program, I'm getting user input via the input("...") function.

The user is supposed to input a list name so I can print it to the console, the problem is that I can only print the list name and not the actual list itself.

Here are my lists:

aaa = [1,2,3,4,5]
bbb = [6,7,8,9,10]

Here is the code I'm using the get the user input:

a = input("Input list name")

Here is the code I'm using to print the list:

print(a)

Here is the expected output:

[1, 2, 3, 4, 5]

Instead this is the output I'm getting:

aaa

Your input is str and you are trying to print string not a list when you do print(a) .

You need to understand str and variable name are not the same thing.

aaa is not same as 'aaa'

You can use dict in this case

# store your lists in dict as below
d = {'aaa': [1,2,3,4,5], 'bbb':[6,7,8,9,10]}

a=input('Input list name: ')

# this will handle if user input does not match to any key in dict
try:
    print(d[a])
except:
    print("Please enter correct name for list")

Output:

[1,2,3,4,5]

Try using the locals() function, like this:

aaa = [1, 2, 3, 4, 5]
bbb = [6, 7, 8, 9, 10]
target = input("What list would you like to see? ")
# NOTE: please don't (I REPEAT DON'T) use eval here
#     : it WILL cause security flaws
#     : try to avoid eval as much as possible
if target in locals():
  found = locals()[target]
  # basic type checking if you only want the user to be able to print lists
  if type(found) == list:
    print(found)
  else:
    print("Whoops! You've selected a value that isn't a list!")
else:
  print("Oh no! The list doesn't exist")

Here is a more concise version of the same code:

aaa = [1, 2, 3, 4, 5]
bbb = [6, 7, 8, 9, 10]

target = input("Enter list name: ")

if target in locals():
  found = locals()[target]
  print(found if type(found) == list else "Value is not a list.")
else:
  print("Target list doesn't exist")

NOTE: in the second answer the code is smaller because I've removed comments, used smaller messages and added a ternary operator.

NOTE: view this answer from this question to find out more about why using eval is bad.

Good luck.

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