python - 使用字典理解将 2 个列表转换为字典
问题描述
我有 2 个列表,我想使用字典理解将其转换为字典。
aa = ['07:51:59', '07:53:35', '07:55:20', '08:01:48']
bb = [50769054, 183926374, 183926374, 183926374]
输出应该是这样的:
{50769054:['07:51:59'], 183926374:['07:53:35', '07:55:20', '08:01:48']}
我正在尝试这种方式:
dictionary ={}
{bb[k]:aa[k] if bb[k] not in dictionary.keys() else dictionary[bb[k]].append(aa[k]) for k in range(0,4)}
但它只给我单一的价值。我的输出:
{50769054: ['07:51:59'], 183926374: ['08:01:48']}
解决方案
@Sushanth 的解决方案是准确的。在这种情况下,您可以像这样使用理解:
from collections import defaultdict
aa = ['07:51:59', '07:53:35', '07:55:20', '08:01:48']
bb = [50769054, 183926374, 183926374, 183926374]
dictionary = defaultdict(list)
[dictionary[y].append(x) for x, y in zip(aa, bb)]
print(dict(dictionary))
输出:
{50769054: ['07:51:59'], 183926374: ['07:53:35', '07:55:20', '08:01:48']}
推荐阅读
- c# - app.config 中的修改在执行项目时没有反映
- machine-learning - 使用 LSTM Keras 的序列数据进行多类分类不起作用
- python - 从其他 python 脚本更改 PyQt 的 QLabel
- java - 因“方法代码太大”而引发 GSP 异常?
- markdown - 通过 Pandoc 将 Markdown 格式的 Agda 读写到 LaTeX
- perl - 如何从perl中的给定json文件中提取键和值
- amazon-web-services - 如何使用 AWS 资源安排“aws s3 sync s3://bucket1 s3://bucket2”?
- json - Wcf 请求总是带有空参数
- java - 通过传递变量动态打开 FXML 接口
- android - NestedScrollView 问题,在两个屏幕之间切换时抛出错误