python - 如何在字典理解中包含 for 循环和 if 语句?
问题描述
我目前正在学习如何使用字典,并且我有点知道如何使用 for 循环进行字典理解。但是我想在 for 循环中包含一个 if 语句。与此类似的东西:
Dict = {}
for i in range(11):
if i < 5:
Dict[i] = 1
else:
Dict[i] = 0
我如何将混乱变成字典理解?
解决方案
Dict = {i: 1 if i < 5 else 0 for i in range(11)}
推荐阅读
- java - 如何在 Android 中按下按钮时播放随机声音?
- json - Python-3 JSON 调用仅在某些系统上从内部模块生成错误
- javascript - IntersectionObserver 是否在加载时弄乱了导航栏?
- excel - 从嵌入的 Excel 对象获取 Visio 形状数据
- json - 如何使用 regex 或 grep 从此 json 中提取 ('uid') 值?
- julia - 朱莉娅的 ST-HOSVD
- node.js - 如何将后端节点 js 服务器连接到反应原生应用程序?
- python - Python 和套接字 - 连接到特定路径
- android - 禁用片段的多个实例
- postgresql - 在 PostgreSQL 数据库中搜索前缀