通过用户输入在字典中创建列表

时间:2017-09-05 13:33:32

标签: python python-3.x dictionary

我是python和编码的新手,我真的不明白为什么我的程序无法正常工作。预期的效果是"名字想要去[目的地]"而我的代码并没有区分不同的" {名称:[目的地]}"对

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

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)

1 个答案:

答案 0 :(得分:0)

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

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