将列表元素与多个列表元素进行比较



我有两个列表:

targets = [ [ [4.88], [2.76], [0.4] ], [ [2.6], [2.12], [7.4], [0.2] ] ]
multiples = [ [ [4.2, 3.6, 6.3], [3.5, 2.5], [7.3, 0.5] ], [ [3.6, 0.3], [5.2, 8.6, 3.7], [3.6, 0.4], [2.3, 6.4] ] ]

对于第一个列表中的每个条目,第二个列表中有多个条目。现在我想比较这些数字,并计算低于 traget 数字的数字的准确性。 我尝试了以下内容,但我不知道如何将一个值与倍数进行比较以及如何同时引用它们。

for element in targets:
tmp = []
for item in element:
tmp2 = []
if item > multiples

输出应如下所示:

[ [ [2], [1], [0] ], [ [1], [0], [2], [0] ] ]

有人知道解决方案吗?

一种使用zip()sum()的解决方案:

targets = [ [ [4.88], [2.76], [0.4] ], [ [2.6], [2.12], [7.4], [0.2] ] ]
multiples = [ [ [4.2, 3.6, 6.3], [3.5, 2.5], [7.3, 0.5] ], [ [3.6, 0.3], [5.2, 8.6, 3.7], [3.6, 0.4], [2.3, 6.4] ] ]
out = []
for val1, val2 in zip(targets, multiples):
out.append([[sum(i < j for i in vval2) for j in vval1] for (vval1, vval2) in zip(val1, val2)])
print(out)

指纹:

[[[2], [1], [0]], [[1], [0], [2], [0]]]
In [4]: [[[len([v for v in vals if v < tg[0]])] for vals, tg in zip(mult, tl)] for mult, tl in zip(multiples, targets)]
Out[4]: [[[2], [1], [0]], [[1], [0], [2], [0]]]

zip内置函数非常适合迭代多个列表。建议的解决方案在很大程度上依赖于它递归压缩您的列表列表。 虽然它是单行代码,但它肯定不是解决您问题的最易读解决方案。

注意len()周围的[]实际上只是为了与所需的输出相匹配。如果省略它,则会得到:

In [5]: [[len([v for v in vals if v < tg[0]]) for vals, tg in zip(mult, tl)] for mult, tl in zip(multiples, targets)]
Out[5]: [[2, 1, 0], [1, 0, 2, 0]]

你写道:">对于第一个列表中的每个条目"。所以我认为你已经嵌套了你的列表来深入......我稍微扁平了你的列表,然后做了:

targets_flat = [
4.88, 2.76, 0.4,
2.6, 2.12, 7.4, 0.2
]
multiples_flat = [
[4.2, 3.6, 6.3], [3.5, 2.5], [7.3, 0.5],
[3.6, 0.3], [5.2, 8.6, 3.7], [3.6, 0.4], [2.3, 6.4]
]
for ref, valuelist in zip(targets_flat, multiples_flat):
lower = [v for v in valuelist if ref > v]
print("reference: {} -> lower: {}".format(ref, lower))

如果您打算使用深层嵌套列表,则必须平展列表(请参阅此处的示例(

相关内容

  • 没有找到相关文章

最新更新