2017-02-12 39 views
1

我想寫一個代碼,詢問不同的用戶他們的夢想度假目的地。這是一個字典,其中的關鍵是民意調查者的名字,值是一個名爲'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 

我當前的代碼不工作,因爲創建的每個按鍵都會有相同的價值觀。

回答

1

嘗試改變

vacation_poll = { } 
dream_vacations = [ ] 
while True: 

vacation_poll = { } 
while True: 
    dream_vacations = [ ] 

他們都有同一個夢想假期的原因,是因爲當你指定dream_vacations,您引用相同的列表。如果在新的人一開始你dream_vacations = [ ],dream_vacations將指向一個entirley無關的列表,所以沒有怪重複

+0

它的工作原理!謝謝! – iluv3142

+0

@ iluv3142請將問題標記爲已回答(點擊您最喜歡的答案旁邊的複選標記),這可以幫助未來的人們解決類似的問題 – Nullman

1

你並不需要創建一個新的變量(我能想到的在任何情況你會想這麼動態)。相反,乾脆爲空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 

這將其設置爲空的列表,所以它現在是空的,並適用於下一個用戶。