- 删除包含特定值得所有列表元素
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 + "。")
本文介绍了Python中如何从列表中删除指定值的所有实例,并展示了如何利用循环和条件语句实现这一目标。此外,还提供了使用用户输入动态填充字典的方法,通过一个简单的调查示例演示了数据收集和展示的过程。
1114

被折叠的 条评论
为什么被折叠?



