【问题标题】:How to index a user input list in Python 2.x?如何在 Python 2.x 中索引用户输入列表?
【发布时间】:2015-10-21 22:34:40
【问题描述】:

希望用户输入他去过的城市的名称,我希望脚本单独存储每个城市。

我使这部分工作正常。

然后,为了项目,脚本应该询问每个城市的位置。但现在,它是这样工作的:

输入:

Paris, Hamburg, London...

输出:

Where is Paris located?
Where is Hamburg located?
Where is London located?
...

代码:

user_cities = raw_input("What cities have you visited so far?").split(", ")
if len(user_cities) > 0:
    index = 0
    for city in user_cities:
        print "Where is "+str(city)+" located?", 
        index+=1

预期输出中缺少一件事:

我们如何索引和/或迭代用户输入列表?我在类似情况下尝试了每段代码,但没有一个对我有用。

我们不知道他去过多少个城市。他只能写 1 个城市或 20 个城市。我可以硬编码,写几十行不必要的行,但我知道有一个正确的方法可以做到这一点。我不记得怎么做了。

在预期的结果中,我希望它轮流向用户一一询问城市在哪里。

输入:

Paris, Hamburg, London...

输出 1:

Where is Paris located?

输入 1:

France

输出 2:

Where is Hamburg located?

输入 2:

Germany

等等

【问题讨论】:

  • 如果您希望它每次都等待用户输入,请使用raw_input,而不是使用print。还有,你用索引做什么...?
  • 您可能希望得到一个包含 {city: country} 条目的字典,然后您可以locations[city] = raw_input("Where is "+str(city)+" located?"
  • 你为什么要使用索引?为什么不是for ... in 循环?
  • @MalikBrahimi 不知道他们为什么使用索引,但他们正在使用for 循环。
  • 这段代码不是已经做了OP想要的吗?我不明白这个问题在问什么。

标签: python list python-2.7 loops indexing


【解决方案1】:

您可以使用带有某种标记的无限循环,让用户指示“不再需要”。怎么样:

cities = []
while True:
    city = raw_input("Enter a city you've been to (or press enter to exit): ")
    if city == '':  # no input -- this is your sentinel
        break  # leave the loop
    else:
        cities.append(city)

然后,如果您出于某种原因想要单独执行此操作,则可以提示输入国家/地区。

countries = []
for idx, city in enumerate(cities):
    country = raw_input("Where is " + city + " located? ")
    countries.append(country)
    # why did you need the index? enumerate is the way to go now....

也许你需要一本字典?

cities_to_countries = dict(zip(cities, countries))

【讨论】:

  • 非常感谢,这正是我所需要的。也感谢其他评论员。我以为我需要索引,但看起来我需要的是字典、枚举和追加。难怪我找不到使用索引的解决方案。
  • @StanleyWilkins 我相信你也可以用索引来做到这一点,但你的“最终结果”应该是什么并不是很明显,所以我很难直接指导你如何获得那里。 enumerate 只是让您在迭代时访问索引,所以...
猜你喜欢
  • 2019-12-23
  • 2021-12-24
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
  • 2021-06-12
  • 2017-07-05
相关资源
最近更新 更多