访问名称来自用户输入的本地变量

时间:2014-12-18 00:21:59

标签: python list

我需要使用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"作为输入给出,它作为字符串而不是列表。 我需要访问上面定义的列表。 我需要一种方法来访问列表并打印列表。

1 个答案:

答案 0 :(得分:1)

使用dict:

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