python - 将不同长度列表的 dict 值转换为一个列表
问题描述
我有作为list
字典给出的数据。字典list
的int
值是不同长度的值。
[{'values': [876.0]},
{'values': [823.0]},
{'values': [828.0]},
{'values': [838.0]},
{'values': [779.0]},
{'values': [804.0, 805.0, 738.0]},
{'values': [756.0]},
{'values': [772.0]},
{'values': [802.0]},
{'values': [812.0]},
{'values': [746.0]},
{'values': [772.0]},
{'values': [834.0, 844.0]},
我想将所有dict
值合二为一(在我的示例代码中list
命名)。rr_intervals
[876.0, 823.0, 828.0, 838.0, 779.0, 804.0, 805.0, 738.0, 756.0, 772.0, 802.0, 812.0, 746.0, 772.0, 834.0, 844.0]
我下面的解决方案工作得很好,但是所有嵌套for
循环都需要一段时间。我想知道是否会有更优雅的解决方案?
rr_intervals = []
for dictionary in rr_list:
for key in dictionary:
if len(dictionary[key]) == 1:
rr_intervals.append(dictionary[key][0])
elif len(dictionary[key]) > 1:
for rr in dictionary[key]:
rr_intervals.append(rr)
解决方案
您可以使用列表推导以 Python 方式实现这一目标,
L = [{'values': [876.0]},
{'values': [823.0]},
{'values': [828.0]},
{'values': [838.0]},
{'values': [779.0]},
{'values': [804.0, 805.0, 738.0]},
{'values': [756.0]},
{'values': [772.0]},
{'values': [802.0]},
{'values': [812.0]},
{'values': [746.0]},
{'values': [772.0]},
{'values': [834.0, 844.0]}]
values = [num for d in L for key, value in d.items() for num in value]
print(values)
输出:
[876.0, 823.0, 828.0, 838.0, 779.0, 804.0, 805.0, 738.0, 756.0, 772.0, 802.0, 812.0, 746.0, 772.0, 834.0, 844.0]
推荐阅读
- reactjs - React 组件确实挂载了,但实际上声明为未挂载
- apache-flink - 有状态的函数 Flink 与 Hbase 和 Redis 的交互
- python - 从按钮显示多个图像
- django - git push Heroku main - 错误:src refspec main 不匹配任何
- java - 偏移量 369250 处的预期 ='endstream' 实际 ='' 错误出现在某些 pdf 中
- powershell - 动力外壳 | 通过使用 csv 或 txt 导入用户获取文件夹 ACL
- c# - 使用 InsightDb 更新到 .Net core 3.1 后,sql 事务无法正常工作
- javascript - 以单个表单发送多个 DIV 容器内容
- azure-databricks - Azure Databricks 中的 Azure eventthub 访问
- python - 在 Graphene/Graphql 中访问数据库 ID