循环以创建新集合-python

循环以创建新集合-python,python,iteration,Python,Iteration,我正在阅读Python的官方教程,在循环部分中,它提出了两种更改字典的策略(作为新手,我发现这很棘手,因为我有时可能会得到这种类型的索引越界错误)。1.创建一个副本,然后2。创建一个新集合 下面是Python官方网站提供的代码(用户列表由我添加) 结果: {'lily':'active','poppy':'active'} def try_loop_new_collection(): users = {'amy': 'inactive', 'lily': 'active', 'popp

我正在阅读Python的官方教程,在循环部分中,它提出了两种更改字典的策略(作为新手,我发现这很棘手,因为我有时可能会得到这种类型的索引越界错误)。1.创建一个副本,然后2。创建一个新集合

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

结果: {'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'}

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)
我在运行这两个程序时得到了相同的结果,但是我无法理解为什么“active_users[user]=status”会以这种方式工作。为什么要将状态分配给活动用户[用户],并设法获得活动用户的完整列表及其在新列表中的状态??我希望能给新手一个善意的解释


提前谢谢。

第一个在迭代过程中更改了词典的大小,因此需要对副本进行迭代

第二种方法填充(修改也可以)一个字典,它不在该字典上进行迭代

经验法则是:如果迭代序列/可变映射,不要在迭代过程中修改其大小

active_users[user] = status
此行使用键
user
更新dict条目。如果条目存在(与您的情况不同),它将用新值覆盖旧值,就像任何变量一样。由于dict中尚不存在该键,因此此行添加了一个新条目,其中包含键
user
和值
status

一次一个条目,该循环将信息从旧的dict复制到新的dict

尝试向代码中添加几个有用的
打印
语句,并观察其工作情况:

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

 amy inactive
{}

 lily active
{'lily': 'active'}

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

“更改列表”?还是“改变字典”?关于
活动用户[user]=status
的工作原理,您还不知道什么?这类似于把一个项目花在一张清单上。在本例中,它将附加ke/value您能详细说明您没有得到它的哪一部分吗?更简单的方法是:
users={user:status for user,status in users.items()if status!='inactive'}
这真的很简洁,谢谢Samwise!你的回答非常有帮助,谢谢!!