1.在列表之間移動元素
#首先創建一個待驗證用戶列表
#再創建一個用于存儲已驗證用戶的空列表
unconfirmed_users=['alice','brian','tom']
confirmed_users=[]
#驗證每個用戶,將每個經過驗證的元素都移到已驗證用戶列表中
#pop()函數每次從列表unconfirmed_users末尾刪除一個的用戶
#title() 方法返回"標題化"的字符串,單詞以大寫開始,其余字母均為小寫
#append() 方法用于在列表末尾添加新的對象
while unconfirmed_users:
curent_user=unconfirmed_users.pop()
print("Verifying user:"+curent_user.title())
confirmed_users.append(curent_user)
#顯示所有已驗證的用戶
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
運行結果:
>>> ================ RESTART: D:\python學習\7.3\confirmed_users.py ================ Verifying user:Tom Verifying user:Brian Verifying user:Alice The following users have been confirmed: Tom Brian Alice >>>
2.刪除包含特定值的所有所表元素
#刪除列表中所有包含特定值的元素
pets=['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print()
print(pets)
運行結果:
====================== RESTART: D:/python學習/7.3/pets.py ====================== ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] ['dog', 'dog', 'goldfish', 'rabbit'] >>>
3.使用用戶輸入來填充字典
#使用用戶輸入來填充字典
#每次循環提示輸入被調查者的名字和回答,收集的數據存放在一個字典中
responses={}
polling_active=True
while polling_active:
name=input("\nWhat's your name?")
response=input("Which mountain would you like to climb someday?")
responses[name]=response#將答案填充到字典中
repeat=input("Y/N?")#設置一個標志,決定是否繼續
if repeat=='N':
polling_active=False
print("\n===========Poll Results========== ") #調查結束,顯示結果
for name,response in responses.items():
print(name+" would like to climb "+response+'.')
'''
注意:
1.填充字典的方法
2.字典輸出的方法
'''
運行結果:
>>> ====================== RESTART: D:/python學習/7.3/填充字典.py ====================== What's your name?張三 Which mountain would you like to climb someday?泰山 Y/N?Y What's your name?Tom Which mountain would you like to climb someday?Alps Y/N?N ===========Poll Results========== Tom would like to climb Alps. 張三 would like to climb 泰山. >>>
浙公網安備 33010602011771號