I have a list and a set:
a_list = [[\'1\', 2], [\'2\', 1], [\'1\', 1]]
b_list = {\'1\', \'2\'}
I\'m looking to correspond the items in b_list
In [1]: a_list = [['1', 2], ['2', 1], ['1', 1]]
...:
...: b_list = {'1', '2'}
In [2]: out = [[i, sum(j[1] for j in a_list if j[0] == i)] for i in b_list]
In [3]: out
Out[3]: [['1', 3], ['2', 1]]
You can use sum of list or you can directly call sum. Here is a time performance of both approach:
In [6]: %timeit [[i, sum(j[1] for j in a_list if j[0] == i)] for i in b_list]
1.31 µs ± 2.52 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [7]: %timeit [[i, sum([j[1] for j in a_list if j[0] == i])] for i in b_list]
1.2 µs ± 1.67 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)