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

for循环是一种遍历列表的有效方式,但不应在for循环中修改列表,否则将导致Python难以跟踪其中的元素. 要在遍历列表的同时对其进行修改,可使用while循环. 通过while循环同列表和字典结合起来使用,可收集、存储组织大量输入,供以后查看和显示.

1 在列表之间移动元素

假设有一个列表包含新注册但还未验证的网站用户. 验证这些用户后,如何将他们移动另一个已验证用户列表中呢?一种办法就是使用while循环,在验证用户的同时将其从未验证用户列表中提取出来,将其加入另一个验证用户列表中. 代码类似如下:

unconfirmed_users = ["alice", "brian", "candace"]
confirmed_users = []

# 验证每个用户,直到没有未验证的用户为止
# 将每个经过验证的用户都移到已验证用户列表中
while unconfirmed_users:
    current_user = unconfirmed_users.pop()

    print(f"Verifying user: {current_user.title()}")
    confirmed_users.append(current_user)


# 显示所有已验证用户
print("\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())


"""
在 VS Code 输出结果:
---------------------
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice
--------------------- 
"""

2 删除为特定值的所有列表元素

我们知道可以通过remove()来删除列表中的特定值. 如果列表中重复项出现一次,还好说,如果出现多次,如:一个宠物列表中,cat出现了3次,难道还一个一个手动删除?其实可以用while循环很好的解决这个问题:

pets = ["dog", "cat", "dog", "goldfish", "cat", "rabbit", "cat"]

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

print(pets)


"""
在 VS Code 输出结果:
---------------------
['dog', 'dog', 'goldfish', 'rabbit']
--------------------- 
"""

3 使用用户输入来填充字典

可使用while循环提示用户输入任意多的信息. 下面创建一个调查程序,其中的循环每次执行时都提示被调查者的名字和回答. 我们将收集的数据存储一个字典中,以便将回答同被调查者关联起来:

reponses = {}

# 设置一个标志,指出调查是否继续 
polling_active = True

while polling_active:
    name = input("\nWhat is your name? ")
    reponse = input("Which mountain would like to climb someday? ")

    # 将回答存储在字典中
    reponses[name] = reponse

    repeat = input("Would you like to let another person respond? (yes/no) ")

    if repeat.title() == "No":
        polling_active = False

print("\n---Poll Results---")
for name, reponse in reponses.items():
    print(f"{name.title()} would like to climb {reponse}.")


"""
在 VS Code 输出结果:
---------------------
What is your name? Eric
Which mountain would like to climb someday? Denali
Would you like to let another person respond? (yes/no) yes

What is your name? Lynn
Which mountain would like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/no) no

---Poll Results---
Eric would like to climb Denali.
Lynn would like to climb Devil's Thumb.
--------------------- 
"""
  • 小练习

1) 熟食店 创建一个名为sandwich_orders的列表, 在其中包含各种三明治的名字,再创建一个名为finished_sandwichs的空列表. 遍历列表sandwich_orders,对于其中的每种三明治,都打印一条消息,并将其移到列表finished_sandwichs中. 所有三明治都制作好后,打印一条消息,将这些三明治残出来:

sandwich_orders = ["tuna", "ham cheese", "chicken breast"]
finished_sandwichs = []

while sandwich_orders:
    sandwich_order = sandwich_orders.pop()
    print(f"I made your {sandwich_order.title()} sandwich.")
    finished_sandwichs.append(sandwich_order)

print("\nThe following sandwich have been made: ")
for finished_sandwich in finished_sandwichs:
    print(f"{finished_sandwich.title()}.")


"""
在 VS Code 输出结果:
---------------------
I made your Chicken Breast sandwich.
I made your Ham Cheese sandwich.
I made your Tuna sandwich.

The following sandwich have been made:
Chicken Breast.
Ham Cheese.
Tuna.
--------------------- 
"""

2) 五香熏牛肉卖完了 在上面一个练习的基础上,在创建的列表sandwich_orders确保"pastrami"在其中至少出现三次,在程序的开头附近添加这样的代码:打印一条消息,指出熟食店的五香熏牛肉(pastrami)卖完了;再使用一个while循环将列表sandwich_orders中的"pastrami"都删除. 确认最终的列表finished_sandwichs未包含"pastrami".

sandwich_orders = ["tuna", "pastrami", "ham cheese","pastrami",  "chicken breast", "pastrami"]
finished_sandwichs = []

print("Pastrami sold out!")
while "pastrami" in sandwich_orders:
    sandwich_orders.remove("pastrami")

while sandwich_orders:
    sandwich_order = sandwich_orders.pop()
    print(f"I made your {sandwich_order.title()} sandwich.")
    finished_sandwichs.append(sandwich_order)

print("\nThe following sandwich have been made: ")
for finished_sandwich in finished_sandwichs:
    print(f"{finished_sandwich.title()}.")


"""
在 VS Code 输出结果:
---------------------
Pastrami sold out!
I made your Chicken Breast sandwich.
I made your Ham Cheese sandwich.
I made your Tuna sandwich.

The following sandwich have been made:
Chicken Breast.
Ham Cheese.
Tuna.
--------------------- 
"""

3) 梦想的度假地 编写一个程序,调查用户梦想的度假胜地.

resorts = {}
active = True

while active:
    name = input("\nWhat's your name? ")
    resort = input("If you could visit one place in the world, where would you go? ")
    resorts[name] = resort

    repeat = input("Would you like to another person repond?(yes/no)")
    
    if repeat.title() == "No":
        active = False

print("\n--resorts--")    
for name, resort in resorts.items():
    print(f"{name.title()} want to visit {resort.title()}.")


"""
在 VS Code 输出结果:
---------------------
What's your name? john
If you could visit one place in the world, where would you go? beijing
Would you like to another person repond?(yes/no)yes

What's your name? pwg
If you could visit one place in the world, where would you go? shanghai
Would you like to another person repond?(yes/no)no

--resorts--
John want to visit Beijing.
Pwg want to visit Shanghai.
--------------------- 
"""

猜你喜欢

转载自blog.csdn.net/2202_75459402/article/details/130528903