如何打印用户通过输入选择的列表?

时间:2019-06-07 10:37:04

标签: python python-3.x list variables

我在python程序中定义了两个列表,我正在通过input("...")函数获取用户输入。

应该向用户输入列表名称,以便我可以将其打印到控制台,问题是我只能打印列表名称,而不能打印实际列表本身。

这是我的清单:

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

这是我在获取用户输入时使用的代码:

a = input("Input list name")

这是我用来打印列表的代码:

print(a)

这是预期的输出:

[1, 2, 3, 4, 5]

这是我得到的输出:

aaa

2 个答案:

答案 0 :(得分:2)

您输入的是str,并且您在执行print(a)时尝试打印字符串而不是列表。

您需要了解str和变量名不是同一回事。

aaa'aaa'

在这种情况下,您可以使用dict

# 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")

输出:

[1,2,3,4,5]

答案 1 :(得分:1)

尝试使用locals()函数,如下所示:

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")

以下是同一代码的更简洁版本:

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")

注意::第二个答案中的代码较小,因为我删除了注释,使用了较小的消息并添加了三元运算符。

注意::从this answer中查看this question,以了解有关使用eval不好的原因的更多信息。

祝你好运。