询问用户并打印列表

Ask user and print a list

我在打印列表时遇到问题。 例如我有两个列表:

a = [1,2,3,4,5]
b = [6,7,8,9,10]

现在我想要求用户输入列表名称,然后打印该列表。

name = input("Write a list name")

用户输入"a"

for x in name:
    print(x)

但它不起作用(不打印列表"a")。你能帮帮我吗?

更多信息:

我有字典:

poland = {"poznan": 86470,
          "warszawa": 86484,
          "sopot": 95266}

并列出:

poznan = [1711505, 163780, 932461, 1164703]

warszawa = [1503333, 93311, 93181, 93268, 106958, 106956, 127649, 106801, 107386, 93245, 154078, 107032]

sopot = [228481, 164126, 922891]

现在,如果用户写入 "poznan",我想将 poznan 的 ID 从字典分配给变量 "city_id",然后打印一个名称为 "poznan"

的列表

您需要将列表映射到用户可以输入的字符串。

所以使用字典:

lists_dict = {
    'a': [1,2,3,4,5]
    'b': [6,7,8,9,10]
}

key = input("Write a list name")

print lists_dict[key]

编辑:

您的词典应如下所示:

poland = {
    "poznan": {"name": 86470, "lst": [1711505, 163780, 932461, 1164703]},
    "warszawa": {"name": 86484, "lst": [1503333, 93311, 93181, 93268, 106958, 106956, 127649, 106801, 107386, 93245, 154078, 107032]},
    "sopot": {"name": 95266, "lst": [228481, 164126, 922891]}
}

访问您的列表应该像这样:

key = input("Write a list name")
# print the list under 'lst' for the dictionary under 'key'
# print poland[key]["lst"]
# EDIT: python 3's print a function, thanks @Ffisegydd:
print(poland[key]["lst"])

您可以像这样使用 globals() 字典 print(globals()[name])input() returns 一个名字,所以也不需要使用循环。

>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> name = input("Write a list name ")
Write a list name a
>>> globals()[name]
[1, 2, 3, 4, 5]

OP编辑后:

>>> poland = {"poznan": 86470,
...           "warszawa": 86484,
...           "sopot": 95266}
>>> poznan = [1711505, 163780, 932461, 1164703]
>>> warszawa = [1503333, 93311, 93181, 93268, 106958, 106956, 127649, 106801, 107386, 93245, 154078, 107032]
>>> sopot = [228481, 164126, 922891]
>>> name = input("Enter name: ")
Enter name: poznan
>>> city_id = poland[name]
>>> city_id
86470
>>> globals()[name]
[1711505, 163780, 932461, 1164703]
>>>