首页 > 解决方案 > 如何在字典理解中包含 for 循环和 if 语句?

问题描述

我目前正在学习如何使用字典,并且我有点知道如何使用 for 循环进行字典理解。但是我想在 for 循环中包含一个 if 语句。与此类似的东西:

Dict = {}
for i in range(11):
    if i < 5:
        Dict[i] = 1
    else:
        Dict[i] = 0

我如何将混乱变成字典理解?

标签: pythonpython-3.xdictionarydictionary-comprehension

解决方案


Dict = {i: 1 if i < 5 else 0 for i in range(11)}

推荐阅读