1. 在列表之間移動元素
unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] # 驗證每個用戶,知道沒有未驗證的用戶 while unconfirmed_users: current_user = unconfirmed_users.pop() print('Verifying user: ' + current_user.title()) confirmed_users.append(current_user) # 顯示所有已經驗證的用戶 print('\nThe following users have been confirmed:') for confirmed_user in confirmed_users: print(confirmed_user.title())
運行結果:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
2. 刪除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
運行結果:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] ['dog', 'dog', 'goldfish', 'rabbit']
若不用while循環,則 pets.remove('cat') 只能移除列表中遇到的第一個 'cat'。
3. 使用用戶輸入來填充字典
responses = { } # 設置一個標志,指出調查是否繼續 polling_active = True while polling_active: # 提示輸入被調查者的名字和回答 name = input('\nWhat is your name? ') response = input('Which mountain would you like to climb someday? ') # 將答案存儲在字典中 responses[name] = response # 看是否還有人要參與調查 repeat = input('Would you like to let another person respond? (yes / no) ') if repeat == 'no': polling_active = False # 調查結束,顯示結果 print('\n--- Polling Result ---') for name, response in responses.items(): print(name + ' would like to climb ' + response + '.')
運行結果:
