首页 > 解决方案 > 循环创建一个新集合

问题描述

我正在阅读 Python 的官方教程,在循环部分中,它提出了两种更改字典的策略(作为新手,我发现这很棘手,因为我有时会为这类事情获取索引超出范围的错误)。1. 创建一个副本,以及 2. 创建一个新集合。

以下是 Python 官网提供的代码(用户列表由我添加)。

def try_loop_iterate_copy():

    users = {'amy': 'inactive', 'lily': 'active', 'poppy': 'active'}
    #Strategy:  Iterate over a copy
    for user, status in users.copy().items():
        if status == 'inactive':
            del users[user]
    print(users)

结果:

{'lily': 'active', 'poppy': 'active'}
def try_loop_new_collection():

    users = {'amy': 'inactive', 'lily': 'active', 'poppy': 'active'}
    # Strategy:  Create a new collection
    active_users = {}
    for user, status in users.items():
        if status == 'active':
            active_users[user] = status
    print(active_users)

结果:

{'lily': 'active', 'poppy': 'active'}

我运行两者都得到了相同的结果,但是我无法理解为什么会active_users[user] = status以这种方式工作。为什么要分配状态active_users[user],并设法在新列表中获取活动用户的完整列表及其状态?我很感激新手的一种解释。

标签: pythondictionaryiteration

解决方案


第一个在迭代期间更改字典大小,因此需要在副本上进行迭代。

第二个填充(修改也可以)一个它没有迭代的字典。

经验法则是:如果您对序列/可变映射进行迭代,请不要在迭代期间修改它的大小


推荐阅读