[英]How do I print a list choosen by the user via input?
我在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
您输入的内容是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]
尝试使用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")
注意:第二个答案中的代码较小,因为我删除了注释,使用了较小的消息并添加了三元运算符。
注:查看这个答案从这个问题 ,以了解更多关于为什么使用eval
是坏的。
祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.