询问用户并打印列表

时间:2015-01-05 13:37:03

标签: python list python-3.x

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

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]

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

的列表

2 个答案:

答案 0 :(得分:11)

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

所以使用字典:

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

答案 1 :(得分:7)

您可以使用此globals()之类的print(globals()[name])字典。 input()返回一个名称,因此无需使用循环。

>>> 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]
>>>