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号