在 for 循环中使用两个变量如何工作

我开始阅读 python 文档。我最终得到了这样的声明:

在迭代同一集合时修改集合的代码可能很难正确处理。相反,循环遍历集合的副本或创建新集合通常更直接:

# Strategy:  Iterate over a copy

for user, status in users.copy().items():

    if status == 'inactive':

        del users[user]


# Strategy:  Create a new collection

active_users = {}

for user, status in users.items():

    if status == 'active':

        active_users[user] = status

我无法理解解决方案。这段代码是如何工作的?我的意思是我想到了使用一个变量来迭代一个列表,但是使用两个变量很难理解。来源:https ://docs.python.org/3/tutorial/controlflow.html#for-statements


精慕HU
浏览 437回答 3
3回答

大话西游666

此代码同时遍历用户和状态:如果用户状态为“非活动”,则程序将在第二个 for 循环中删除该用户 如果用户为“活动”,它将将此用户添加到活动用户字典中,当你想要要同时循环遍历字典的键值对,必须使用 dict.items() 方法,items() 方法允许您同时循环遍历每个字典元素(或元组)的项,这里的项目是用户和状态,这就是为什么还有2个迭代变量也命名为用户和状态

幕布斯6054654

我也有同样的困惑。给出的示例不起作用。缺少的部分是开头的字典对象“用户”。在本教程的那个时候,我们还没有被告知它们。https://docs.python.org/3/library/stdtypes.html#index-50工作版本是users = { "John": "inactive",                "Helen": "active",               "James": "active", # and so on...            }# Strategy:  Iterate over a copyfor user, status in users.copy().items():    if status == 'inactive':        del users[user]# Strategy:  Create a new collectionactive_users = {}for user, status in users.items():    if status == 'active':        active_users[user] = status如果您想查看内容,则可以将其打印出来。尝试这个:users = { "John": "inactive",                "Helen": "active",               "James": "active", # and so on...            }# Strategy:  Iterate over a copyfor user, status in users.copy().items():    if status == 'inactive':        del users[user]print("Users after deleting.")for user, status in users.items():    print(user, status)users = { "John": "inactive",                "Helen": "active",               "James": "active", # and so on...            }# Strategy:  Create a new collectionactive_users = {}for user, status in users.items():    if status == 'active':        active_users[user] = statusprint("active_users.items")for user, status in active_users.items():    print(user, status)

交互式爱情

简单示例:假设您有一本实体电话簿,并想在其中查找朋友或家人。Python中的等价物是:phone_book = { "Mom": "123-456-7890",                "Dad": "123-456-7891",               "John Doe": "555-555-5555", # and so on...            }如果您尝试在实体电话簿中查找您父亲的电话号码,您可以通过直接导航到您所写的页面并找到该条目来实现。同样,在 Python 字典中查找也是一样的:print(phone_book['Dad']) # 123-456-7891现在现实世界的例子已经很清楚了,看看你的例子。通过.items(),您正在检索一个键值对,其中user只是引用users字典中特定值的键(如“妈妈”或“爸爸”),并且status是映射到该特定值的值user(如他们的电话号码)。但是,您正在获取users字典的副本,以便您可以遍历usersto的整个配对statuses。如果你有for user, status in users.items():   del[user]您将修改您尝试迭代的字典并且会出现错误。为避免这种情况,您正在制作它的临时副本以迭代并从中删除实际副本user(users想想“从电话簿中删除妈妈”)。在第二个块中,您正在将人员添加到活动用户字典中。想想“将 Billy 添加到电话簿,电话号码为“111-222-3344”,但在这种情况下,您要添加user和它们对应的status.TLDR:字典只是查找内容的一种方式,但是为了查找内容,您需要知道它们的标识符(name在电话簿中,user在用户字典中)。number如果您想使用该标识符的值(在电话簿、用户字典中)做某事status,您需要暂时存储它,直到您完成它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python