【问题标题】:making lists in a dictionary by user inputs通过用户输入在字典中创建列表
【发布时间】:2017-09-05 13:33:31
【问题描述】:

我是 python 和编码方面的新手,我真的不明白为什么我的程序不能正常工作。预期的效果是“名称想要去 [destinations]”,而我的代码没有区分不同的“{names : [destinations]}”对。

这是我的代码,感谢您的关注:)

response = {}
destinations = []
ptname = 'name pls.'
prompt = 'input some places in the world, input next to go to the next user'
active = True
unfinished = True
while active:
  unfinished = True
  name = input(ptname)
  while unfinished:
    destination = input(prompt)
    if destination != 'next':
      destinations.append(destination)
      print(destination + ' has been added to your list.')
      response[name] = destinations
    elif destination == 'next':
      unfinished = False
  go_on = input('wish to continue? y/n')
  if go_on == 'n':
    active = False

print(response)
for name, destinations in response.items():
  print(name + ' wants to go to ')
  for destination in destinations:
    print(destination)

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    您必须在设置 name 的同一个外部循环中为 destinations 重置(实际上是创建一个新的引用),否则您将对所有名称重复使用相同的列表。

      name = input(ptname)
      destinations = []   # create new reference for the list
      while unfinished:
      ...
    

    【讨论】:

    • 如何在 while=unfinished 循环中生成新列表,以及如何在字典 {response} 中使用用户名索引新列表名
    猜你喜欢
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多