while循環 操作列表與字典
1、在列表間移動元素
#!/usr/bin/env python
#filename=list.py
num1 = [1,3,5,7,9,11,13,15]
num2 = []
while num1:
interest_number = num1.pop()
num2.append(interest_number)
print(num2)
#實例是一個最簡單的在列表間移動元素的腳本#
會發現效果是:
[[email protected] Day3]# ./list.py
[15, 13, 11, 9, 7, 5, 3, 1]
因為num1.pop()是從最後一個開始pop的,所以導致整個mun2是ASSIC逆序的,可以通過函數sort()來進排序
while num1:
interest_number = num1.pop()
num2.append(interest_number)
num2.sort()
print(num2)
[[email protected] Day3]# ./list.py
[1, 3, 5, 7, 9, 11, 13, 15]
刪除列表中的特定元素:
註意看如下代碼
>>> pets = [ ‘dog‘, ‘cat‘, ‘rabbit‘, ‘goldfish‘,‘cat‘]
>>> pets.remove(‘cat‘)
>>> pets
[‘dog‘, ‘rabbit‘, ‘goldfish‘, ‘cat‘]
有一個寵物列表“pets”,其中多次出現了‘cat’這個元素,現在需要從此列表中移除‘cat’元素,
使用之前的list.remove(‘ ’)會發現只是把位於第一個index的cat刪除了。沒有移除所有,這個時候需要使用到while循環來幫忙了
代碼段:
#!/usr/bin/env python
#filename while_list.py
pets = [ ‘dog‘,‘cat‘,‘goldfish‘,‘cat‘,‘pig‘]
while ‘cat‘ in pets:
pets.remove(‘cat‘)
print(pets)
根據用戶輸入來填充字典:(例如,問卷調查)
#!/usr/bin/env python
#filename=questionnaire.py
love_av = {} #定義一個空字典#
polling_active = True
while polling_active:
name = input("\n What is your name? :") #第一個input存放到變量 name#
response = input("\n Which actor do you like better? (Takizawa Rola/Maria Ozawa) :") #第二個input存放到變量 response#
love_av[name] = response #編輯字典 name為鍵,response為值#
repeat = input("\n Do you have any other hobbies? (yes/no) :")
if repeat == ‘no‘:
polling_active = False
print("\n -----Poll Results-----")
for name,response in love_av.items():
print(name.title() + " prefer " + response.title())
這段交互代碼有一個缺陷:
就是當用戶輸入的是yes/no選項出現大小寫混搭的時候,程序無法區分。
改進——
把repeat 變量進行一次轉換
repeat = repeat.upper() #無論輸入什麽。全部轉化為大寫 #
if repeat == ‘NO‘:
polling_active = False
這時候,不管用戶輸入No\nO\NO\no 都可以被程序所識別。
while循環 操作列表與字典