欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

7.3 使用while 循环来处理列表和字典

程序员文章站 2023-10-31 11:57:22
# 7.3.1 在列表之间移动元素 # confirmed_users.py # 首先,创建一个待验证用户列表 # 和一个用于存储已验证用户的空列表 uncomfirmed_users = ['james','star','wendy'] comfirmed_users = [] # 验证每个用户, ......

# 7.3.1 在列表之间移动元素

# confirmed_users.py

# 首先,创建一个待验证用户列表

# 和一个用于存储已验证用户的空列表

uncomfirmed_users = ['james','star','wendy']

comfirmed_users = []

# 验证每个用户,直到没有未验证用户为止

# 将每个经过验证的列表都移到已验证用户列表中

while uncomfirmed_users:
  current_user = uncomfirmed_users.pop()  # pop.() 默认移除列表中最后一个元素

  print("verifying use: " + current_user.title())
  comfirmed_users.append(current_user)  # 空列表已经在这段码块中更新
# 显示所有已验证的用户
print("\nthe following users have been comfirmed:")
for comfirmed_user in comfirmed_users:
  print(comfirmed_user.title())

 

# 7.3.2 删除包含特定值的所有列表元素
#pets.py
pets = ['dog','cat','goldfish','cat','rabbit','tigger','cat','chick']

# 循环寻找列表中的'cat',并且移除所有'cat',直到列表中没有这条信息

while 'cat' in pets:
  pets.remove('cat')

print(pets)

# 7.3.3 使用用户输入来填充字典
# mountain_poll.py
responses = {}
polling_active = true

while polling_active:

# input()函数,提示用户需要输入信息
name = input("what's your name?")
response = input("which mountain would you like to climb someday?")

# 字典 {'keys','values'} 等效于 keys = values,name = response

responses[name] = response

repeat = input("would you like to let another person repond? (yes/no)")
if repeat == 'no':
polling_active = false

print("\n---poll result---")
for name, response in responses.items():
print(name.title() + " would like to climb " + response + ".")

# 7-8 熟食店
sandwich_orders = ['tomato','potato','vegetable']
finished_sandwiches = []

while sandwich_orders:
  current_sandwich = sandwich_orders.pop()

print(current_sandwich + ", i made your tuna sandwich.")
finished_sandwiches.append(current_sandwich)

print("all the sandwiches are finished.")
for finished_sandwich in finished_sandwiches:
  print(finished_sandwich.title())

# 7-9 五香烟熏牛肉
sandwich_orders = ['tomato','pastrami','potato','pastrami','vegetable','pastrami']
finished_sandwiches = []
while 'pastrami' in sandwich_orders:
  sandwich_orders.remove('pastrami')

print("pastrami sold out!")

while sandwich_orders:
  current_sandwich = sandwich_orders.pop()

print(current_sandwich + ", i made your tuna sandwich.")
finished_sandwiches.append(current_sandwich)

print("all the sandwiches are finished.")
for finished_sandwich in finished_sandwiches:
  print(finished_sandwich.title())

# 7-10 梦想的度假胜地

responses = {}

polling_active = true
while polling_active:
  name = input("what's your name?")
response = input("if you could visit one place in the world," +
" where would you go?")
responses[name] = response

repeat = input("would you like to let another person respond? (yes/no) ")
if repeat == 'no':
  polling_active = false

print("---poll result---")
for name, response in responses.items():
  print(name.title() + " would like to visit " + response + ".")