Reputation: 494
I have two lists:
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] ] ]
For every entry in the first list, there are multiple entries in the second one. Now I want to compare these numbers and count the accurences of the numbers that are lower than the traget number. I tried the following, but I don't know how I can compare one single value with multiples and how to refer simultaniously to them.
for element in targets:
tmp = []
for item in element:
tmp2 = []
if item > multiples
The output should be something like this:
[ [ [2], [1], [0] ], [ [1], [0], [2], [0] ] ]
Does somebody know a solution?
Upvotes: 1
Views: 72
Reputation: 10957
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]]]
The zip
built-in function is ideal to iterate over multiple lists. The proposed solution heavily relies on it zipping recursively your lists of lists.
While it is a one-liner it is certainly not the most readable solution to your problem.
Note: The []
around len()
is really just to match with the desired output. If you omit it you get:
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]]
Upvotes: 1
Reputation: 247
you wrote: 'For every entry in the first list'. So i think you have nested your lists to deep... i flattened your lists a bit and did:
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))
If the deep nested lists are your intention so you must flatten the lists (see here an example)
Upvotes: 1
Reputation: 195408
One solution using zip()
and 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)
Prints:
[[[2], [1], [0]], [[1], [0], [2], [0]]]
Upvotes: 2