首页 > 解决方案 > 如何基于另一个嵌套列表将缺失值附加到嵌套中?

问题描述

我有一个嵌套列表:

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

我怎样才能正确地做到这一点?

标签: pythonlist

解决方案


实际上,您正在使用嵌套列表,因为它们是字典,所以我会将它们转换为普通字典以便更轻松地处理:

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

推荐阅读