python - 循环创建一个新集合
问题描述
我正在阅读 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]
,并设法在新列表中获取活动用户的完整列表及其状态?我很感激新手的一种解释。
解决方案
第一个在迭代期间更改字典大小,因此需要在副本上进行迭代。
第二个填充(修改也可以)一个它没有迭代的字典。
经验法则是:如果您对序列/可变映射进行迭代,请不要在迭代期间修改它的大小。
推荐阅读
- amazon-web-services - AWS passive failover pricing
- android - 从大整数设置进度条的最大值
- javascript - 以角度 6 将 Json 字符串转换为 json 数组
- hadoop - 从 Oracle 导入 Sqoop 失败,出现“线程“主”java.lang.NoClassDefFoundError:org/apache/hadoop/mapreduce/InputFormat 中的异常”
- machine-learning - 位置坐标表示
- python - 保存原始 html 表单 django
- c - 在C中找到一个数字的无平方除数
- java - 在收集应用程序中添加下载按钮
- rabbitmq - 将“amq.rabbitmq.event”交换配置到不同的虚拟主机?
- c# - C#- 使用 MySQL 执行命令时发生致命错误