my arrays are:
array a = [[123, 'a', 'b', 'd'], [253, 'f', 'c'], [322, 's', 'b']]
// each sub-array contains serial no. and strings.
array b = [['a', 2], ['s', 4], ['b', 1]]
// each sub-array contains string and score.
The required result is:
array result = [[123, 3],[322, 5]]
// each sub-array contains serial no. from array a and sum of scores according to the string in it and their scores from array b (if score is zero so don’t write to result array)
I know how to do it using nested for loops for arrays a and b and sum it and append to array result, but I wonder if there is more efficient way, like using dict. or anything else.
thanks!
>Solution :
Try:
array_a = [[123, "a", "b", "d"], [253, "f", "c"], [322, "s", "b"]]
array_b = [["a", 2], ["s", 4], ["b", 1]]
tmp = dict(array_b)
out = [
[id_, s]
for id_, *vals in array_a
if (s := sum(tmp.get(v, 0) for v in vals)) != 0
]
print(out)
Prints:
[[123, 3], [322, 5]]