Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Most effective way to compare 2 arrays and write to third in python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading