如何在每次引入新键时为列表创建新变量



我正在尝试编写一个代码,询问不同的用户他们梦想中的度假胜地。这是一个字典,其中键是投票者的名字,值是一个名为"dream_vacations"的列表。我想在创建新键时创建一个新变量。最好的方法是什么?

vacation_poll = { }
dream_vacations = [ ]
while True:
    name = input('What is your name?: ')
    while True:
        dream_vacation = input('Where would you like to visit?: ')
        repeat = input('Is there anywhere else you like to visit? (Yes/No): ')
        dream_vacations.append(dream_vacation)
        if repeat.lower() == 'no':
            vacation_poll[name] = dream_vacations
            break
    new_user_prompt = input('Is there anyone else who would like to take the poll? (Yes/No): ')
    if new_user_prompt.lower() == 'no':
         break

我当前的代码不起作用,因为创建的每个键都具有相同的值。

尝试更改

vacation_poll = { }
dream_vacations = [ ]
while True:

vacation_poll = { }
while True:
    dream_vacations = [ ]

他们都有相同的梦想假期的原因是,当您分配dream_vacations时,您引用的是相同的列表。 如果你dream_vacations = [ ]一个新人的开头,dream_vacations会指向一个完全不相关的列表,所以没有奇怪的重复

你不需要

创建一个新变量(我想出你想要如此动态的情况(。相反,每次只需清空dream_vacations,即:

new_user_prompt = input('Is there anyone else who would like to take the poll? (Yes/No): ')
dream_vacations = []
if new_user_prompt.lower() == 'no':
     break

这会将其设置为空白列表,因此它现在为空,适用于下一个用户。

最新更新