使用while循環來處理列表和字典——參考Python編程從入門到實踐


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 + '.')

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM