Python- 将 While 循环与列表和字典一起使用

liftword4周前 (04-05)技术文章4

处理多个用户输入:

  • While 循环可以通过将多个输入存储在列表或字典中来收集和管理它们。
  • 与 for 循环不同,while 循环可以在执行过程中修改列表,使其可用于动态管理数据(如用户输入)。

在列表之间移动数据:

可以使用 while 循环将数据从一个列表传输到另一个列表。

在此示例中,我们从未经验证的用户列表和已确认用户的空列表开始。在验证每个用户时,我们使用 while 循环将他们从未验证列表移动到已确认列表。

# Start with users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
    current_user = unconfirmed_users.pop()  # Remove the last unverified user
    print(f"Verifying user: {current_user.title()}")
    confirmed_users.append(current_user)  # Add the user to the confirmed list

# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

>>

Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice
  • 只要 while 循环不为空unconfirmed_users 就会运行。
  • pop() 方法从 unconfirmed_users 中删除最后一个用户并将其分配给 current_user
  • 每个经过验证的用户都使用 append() 添加到 confirmed_users
  • 确认所有用户后,循环结束,程序将打印已确认的用户。

从列表中删除特定值:

要删除特定值的所有实例(例如,从列表中删除所有 'cat' 条目),请使用 while 循环。

假设我们有一个包含特定值的多个实例的列表,例如 'cat',并且我们想要删除所有匹配项。while 循环反复删除 'cat',直到没有剩余。

# List of pets with multiple 'cat' entries
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print("Original list of pets:", pets)

# Remove all instances of 'cat' from the list
while 'cat' in pets:
    pets.remove('cat')

print("Updated list of pets:", pets)

>>

Original list of pets: ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
Updated list of pets: ['dog', 'dog', 'goldfish', 'rabbit']
  • while 循环检查 pets 列表中是否仍存在 'cat'。
  • 如果找到 'cat',它会使用 remove() 删除它的第一个匹配项。
  • 循环重复,直到删除 'cat' 的所有实例。

用用户输入填充字典:

while 循环可以收集用户的输入并将其存储在字典中,从而将用户的响应与其姓名相关联。

在此示例中,我们创建一个投票程序,在该程序中向用户提出问题,并将他们的答案存储在字典中。每个用户的名称是键,他们的响应是值。

# Empty dictionary to store responses
responses = {}

# Set a flag to indicate that polling is active.
polling_active = True

while polling_active:
    # Prompt for the person's name and response
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")

    # Store the response in the dictionary
    responses[name] = response

    # Ask if another user wants to respond
    repeat = input("Would you like to let another person respond? (yes/no) ")
    if repeat.lower() == 'no':
        polling_active = False

# Polling is complete, display the results
print("\n--- Poll Results ---")
for name, response in responses.items():
    print(f"{name} would like to climb {response}.")

>>


What is your name? Nidhi
Which mountain would you like to climb someday? Mount Everest
Would you like to let another person respond? (yes/no) yes

What is your name? Nid
Which mountain would you like to climb someday? Eastern Himalaya        
Would you like to let another person respond? (yes/no) no

--- Poll Results ---
Nidhi would like to climb Mount Everest.
Nid would like to climb Eastern Himalaya.
  • 只要 polling_activeTrue,while 循环就会一直运行。
  • 该程序会提示用户输入他们的名字和他们想要攀登的山峰。
  • 响应存储在 responses 字典中,其中 key 是用户名,value 是他们的响应。
  • 然后,系统会询问用户是否要允许其他人响应。如果他们键入 'no',则循环通过设置 polling_active = False 结束。
  • 轮询结束后,程序将打印所有响应。

相关文章

Python基础教程——列表(一)

列表由一系列按特定顺序排列的元素组成。列表是最常用的Python数据类型。在Python中,用方括号([ ])来表示列表,并用逗号来分隔其中的元素。如下面这个列表:这个列表中有四种编程语言,如果让Py...

Python列表操作

Python添加列表4 分钟阅读在 Python 操作列表有各种方法。例如 – 简单地将一个列表的元素附加到 for 循环中另一个列表的尾部,或使用 +/* 运算符、列表推导、extend() 和 i...

Python快速入门教程2:列表

一、列表简介列表(list)是Python中的一种有序且可变的序列类型。它可以存储多个元素,并允许重复元素。列表中的元素可以是不同类型的数据,如整数、字符串、其他列表等。创建列表使用方括号[]创建列表...

每日一练用Python如何输出列表

设置了一个列表,我想输出它,我怎么输出呢?可能很多人感觉我不用到列表,其实就是一个的简单的动作,和我们平常工作一样,经常频繁做一些事情,鼓噪无畏。但还是要学会去弄。当我们列表里面是孩子的成绩,你肯定...

一文掌握如何在 Python 中创建空列表

空列表是许多 Python 程序的起点,无论您是收集用户输入、处理数据还是构建动态数据结构。让我们探索在 Python 中创建和使用空列表的所有方法。创建空列表的基本方法使用方括号创建空列表的最常见和...

Python之列表(list)

基础概念列表是什么:像一个有序的"容器",可以装多个元素(数字、字符串、列表、字典等),元素用逗号分隔,用 [] 包裹。特点:有序(有下标)、可重复、元素可以修改简单案例# 案例 1:创建一个水果列表...