简体   繁体   English

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

[英]making lists in a dictionary by user inputs

I'am a newbee in python and coding, and I really don't understand why my program isn't working correctly. 我是python和编码方面的新手,我真的不明白为什么我的程序无法正常工作。 The expected effect is "name wants to go to [destinations]" while my code doesn't distinguish different "{names : [destinations]}" pairs. 预期的效果是“名称想转到[目标]”,而我的代码没有区分不同的“ {names:[目标]}”对。

Here's my code, thanks for your attention here :) 这是我的代码,感谢您的关注:)

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)

you have to reset (actually create a new reference) for destinations in the same outer loop where you set name or you're be reusing the same list for all names. 您必须在设置name的同一外部循环中重置(实际上创建一个新引用) destinations ,否则您将对所有名称重用同一列表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM