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

liftword4个月前 (12-18)技术文章55


处理多个用户输入:

  • 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基础##python编程##python#一、Python 字典创建概述介绍 Python 中创建字典的多种方法,对于不同场景有不同的适用方式。Python 是一种功能强大的编程语...

Python教程-字典 字典 python

作为软件开发者,我们总是努力编写干净、简洁、高效的代码。在这篇文章中,我们将介绍你需要知道的关于Python中字典的一切,包括它们是什么,它们如何工作,以及如何在你的代码中有效地使用它们。什么是 Py...

Python 动手练:字典 python的字典怎么用

字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值对用冒号 : 分隔( key:value ),每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中。键一般是唯一的,如果重复最后...

python之字典处理 python 中字典

1,访问字典dict['key']#用于返回指定键的值,也就是根据键来获取值,在键不存在的情况下,返回 None,也可以指定返回值。dict.get(key)2, 修改字段dict[&...

RealPython 基础教程:Python 字典用法详解

在连续编写了5篇和 list 相关的文章之后,我们继续《RealPython 基础教程》这个系列。今天,我们要学习的数据结构是字典(dict)。dict 是一个包含若干对象的集合。它和 list 有以...

在 Python 中将字典内容保存到 Excel 文件

Python 中的字典是一个数据集合,其中每个值对应一个键。它们是无序的、可变的,并且对字典中存储的值和键的数据类型没有限制。Python 程序员经常需要在不同格式之间传输数据,将字典导出到 Exce...