- for循环是遍历列表的有效方式,但不应在for循环中修改列表,否则导致Python难以跟踪其中的元素。
- 使用while循环,在遍历的同时进行修改。while循环+列表+字典--→收集、存储、组织大量输入,供以后查看和显示。
1.在列表之间移动
假设一个列表包含新注册但还未验证的网站用户,验证后,将他们移至另一列表。
#首先,创建一个待验证用户列表和一个存储已验证用户的空列表。 unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] #验证每个用户直到没有未验证用户为止。 # 并将经过验证的用户移至已验证用户列表中。 while unconfirmed_users: currents_user = unconfirmed_users.pop() print(f"Verfying user:{currents_user.title()}") confirmed_users.append(currents_user) #显示所有已验证用户 print("\nThe following users have been confirmed.:") for confirmed_user in confirmed_users: print(confirmed_user.title())
讯享网

讯享网
- pop方法以每次一个的方式从列表末尾删除元素。
- append的用法:元素作为方法的参数传递过去的(中间变量不可少)。删除为特定值的列表元素
2.删除列表中特定值
讯享网pets = ['dog', 'cat', 'goldfish', 'rabbit', 'dog', 'cat', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
- 方法remove一次只能删一个特定元素。
在这里产生的一个疑惑:方法里有参数吗?于是,搜了搜方法与函数的区别。函数是在C中就有的,方法可能是C++里面和类关联起来才有的?简单理解是:函数是独立的,方法需要依附对象。函数和方法的区别_我_是好人的博客-CSDN博客_函数和方法
https://blog.csdn.net/_/article/details/
3.使用用户输入来填充字典
#创建一个空字典 responses = {} #设置一个标志,指出调查是否继续 polling_active = True while polling_active: #提示输入被调查者名字和回答 name = input("/nWhat's your name? ") response = input("Which mountain would you like to climb? ") #将答案存储在字典中 responses[name] = response #看看是否还有人要参与 repeat = input("Would you like to let others respond? (Y/N)") if repeat == 'N': polling_active = False #调查结束,显示结果 print("\n---Poll Results---") for name, response in responses.item(): print(f"{name} would like to climb {response}")

- 此字典的键对值
4. 课后练习
讯享网#7-8 熟食店 sandwish_orders = ['fish-sandwish', 'beef-sandwish', 'chicken-sandwish'] finished_sandwishes = [] while sandwish_orders: current_sandwish = sandwish_orders.pop() print(f"{current_sandwish},I made your tuna sandwish.") finished_sandwishes.append(current_sandwish) print("\nAll the sandwish were made: ") print(finished_sandwishes) #7-9 五香烟熏肉卖完了 sandwish_orders = ['pastrami', 'fish-sandwish', 'pastrami', 'beef-sandwish', 'pastrami', 'chicken-sandwish', 'beef-sandwish', 'chicken-sandwish'] print("\npastrami sold out") while 'pastrami' in sandwish_orders: sandwish_orders.remove('pastrami') print(sandwish_orders) #7-10 梦想的度假胜地 vacationlands = {} flag = True while flag: name = input("What's your name? ") place = input("Where would you want to go? ") vacationlands[name] = place flag = input("would you want to continue? (True/False)\n") print(f"\n{name} would like to {place}")
这里由于当时没设置制表符,显得有点“拥挤”。最后地方输入“False”却不能成功退出程序,是因为上一篇里说过的input()函数de原因。 修改如下:
temp = input("would you want to continue? (Y/N)") if temp == 'N': flag = False

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/117363.html