gpt4 book ai didi

python - 访问名称来自用户输入的局部变量

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:03 25 4
gpt4 key购买 nike

我需要使用raw_input访问字符串。

list1 = ["one","Two","three"]

list2 = ["1","2","3"]

while True:

ip = raw_input("enter list: ")
for i in ip:
print i
break

当“list1”作为输入给出时,它采用字符串而不是列表。我需要访问上面定义的列表。我需要一种访问列表并打印列表的方法。

最佳答案

使用字典:

lists = {
"list1": ["one","Two","three"],
"list2": ["1","2","3"],
}

while True:
choice = raw_input("enter the list name: ")
try:
for item in lists[choice]:
print item
except KeyError:
print "I never heard of any list named '{}'! Try again.".format(choice)
else:
break

关于python - 访问名称来自用户输入的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27537230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com