1. 程式人生 > >Python入門學習(4)

Python入門學習(4)

  1. 刪除包含特定值得所有列表元素
pets = ['cat','dog','goldfish','cat','rabit','cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

執行結果如下:

[‘cat’, ‘dog’, ‘goldfish’, ‘cat’, ‘rabit’, ‘cat’]
[‘dog’, ‘goldfish’, ‘rabit’]

2 . 使用使用者輸入來填充字典

responses = {}

# 設定一個標誌,指出調查是否繼續
polling_active = True while polling_active: name = input("你叫什麼名字?") response = input("將來有一天你想去哪個城市?") # 將答案儲存在字典中 responses[name] = response # 看看是否還有人要參與調查 repeat = input("還有沒有人要回答?") if repeat == 'no': polling_active = False # 調查結束,顯示結果 print("\n--------調查結果--------"
) for name,response in responses.items(): print(name + "想去" + response + "。")