将元组列表列表转换为 dict 未按预期工作

conversion of list of list of tuples to dict not working as expected

我正在尝试为这个包含元组的列表列表创建 dict。目的是将需要的元组过滤到最终列表中。

到目前为止我尝试过的:

dict_1 = dict()
for val,sim in result:
    dict_1.setdefault(val, [])


print(result)

当我查看结果并解压缩两个值 (val,sim) 时,它工作正常。但是每次我得到的情况都不一样,可能有多个值要解包然后它会给出这个错误:

ValueError: too many values to unpack (expected 2).

如何使上面的循环for val,sim in result:灵活?

这是输入格式:

[[(1.0, 2481), (0.125, 5)], [(1.0, 2481), (0.10526315789473684, 1), (0.0, 5), (0.0, 4), (0.0, 3), (0.0, 2)], [(1.0, 2481), (0.11764705882352941, 2), (0.0, 5), (0.0, 4), (0.0, 3), (0.0, 1)], [(1.0, 2481), (0.13333333333333333, 3), (0.0, 5), (0.0, 4), (0.0, 2), (0.0, 1)], [(1.0, 2481), (0.1, 4), (0.0, 5), (0.0, 3), (0.0, 2), (0.0, 1)]]

我的最终目标是先制作字典,然后开始过滤元组我只对具有特定值 sim 的元组 [(value,sim), (value,sim)] 感兴趣,但在此之前我陷入了困境以上部分。

期望的输出:

[(1.0, 2481), (0.125, 5), (0.10526315789473684, 1),(0.11764705882352941, 2), (0.13333333333333333, 3), (0.1, 4)]

我只是一个初学者。我知道这可能不是提问的正确方式。但是任何一种正确方向的小指导都将不胜感激!

您可以尝试嵌套切片:

a = [[(1.0, 2481), (0.125, 5)], 
     [(1.0, 2481), (0.10526315789473684, 1), (0.0, 5), (0.0, 4), (0.0, 3), (0.0, 2)], 
     [(1.0, 2481), (0.11764705882352941, 2), (0.0, 5), (0.0, 4), (0.0, 3), (0.0, 1)], 
     [(1.0, 2481), (0.13333333333333333, 3), (0.0, 5), (0.0, 4), (0.0, 2), (0.0, 1)], 
     [(1.0, 2481), (0.1, 4), (0.0, 5), (0.0, 3), (0.0, 2), (0.0, 1)]]

b = [a[0][0]] + [i[1] for i in a]

print(b)

输出:

[(1.0, 2481), 
 (0.125, 5), 
 (0.10526315789473684, 1), 
 (0.11764705882352941, 2), 
 (0.13333333333333333, 3), 
 (0.1, 4)]