python - 如何基于另一个嵌套列表将缺失值附加到嵌套中?
问题描述
我有一个嵌套列表:
pw = [[[1, 0.020387050117001683],
[2, 0.023095733958878487]],
[[1, 0.020387050117001683],
[2, 0.023095733958878487],
[3, 0.05133549261794933]]]
子列表缺少特定值,我将其存储在另一个嵌套中:
nl = [[0 ,0.01], [3, 0.01]]
子列表 1 缺少 0 和 3 的条目index 0
,而子列表 2 缺少 0 的条目index 0
。
我想要的结果是这样的:
pw = [[[0 ,0.01],
[1, 0.020387050117001683],
[2, 0.023095733958878487]
[3 ,0.01]],
[[0 ,0.01],
[1, 0.020387050117001683],
[2, 0.023095733958878487],
[3, 0.05133549261794933]]]
但是我的代码:
for line in pw:
for l in line:
for f in nl:
if not any (f[0] in l[0] for f in nl):
l.append(f)
产生此错误:
TypeError: argument of type 'int' is not iterable
我怎样才能正确地做到这一点?
解决方案
实际上,您正在使用嵌套列表,因为它们是字典,所以我会将它们转换为普通字典以便更轻松地处理:
hpw = [dict(i) for i in pw] # convert nested list to dicts
for h in hpw: # add missing values to the dicts
for i in nl:
if i[0] not in h:
h[i[0]] = i[1]
pw = [sorted([[k,v] for k,v in h.items()]) for h in hpw] # convert back to sorted nested lists
推荐阅读
- wpf - 设置 .NET Core 和 .NET Standard 桌面应用程序以进行发布
- batch-file - 如果我运行批处理文件时没有执行 ELSE
- serial-port - 如何在python中将3个连接的字符串更改为字节?
- wix - 我的产品版本号的第三部分(1.0.X)没有填充到4位
- python - FTP 连接在 FileZilla 和命令行上工作,但不是 python ftplib
- php - 无法从 AngularJS 调用 php
- c# - 如何使用 C# 找到通过 USB 电缆连接的相机,然后我可以复制存储的图像
- google-cloud-platform - Cloud Pub Sub 和 Logs Viewer EventId 问题触发的 Cloud Functions
- java - Kafka 依赖项 - ccs 与 ce
- node.js - Mac 节点串口未检测到连接的 USB 设备