Home > Software design >  Most effective way to compare 2 arrays and write to third in python
Most effective way to compare 2 arrays and write to third in python

Time:04-07

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!

CodePudding user response:

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]]

CodePudding user response:

You can also use a dict comprehension and list comprehension:

a = [[123, 'a', 'b', 'd'], [253, 'f', 'c'], [322, 's', 'b']]
b = [['a', 2], ['s', 4], ['b', 1]]
b_dict = {part[0]:part[1] for part in b}
result = [part for part in [[elem[0], sum([b_dict.get(string, 0) for string in elem[1:]])] for elem in a] if part[1]]

The value of result is now:

[[123, 3], [322, 5]]
  • Related