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
You are on the right track! All you have to do is flip the order of your loops. For every value in b_list
, you want to sum up all matching values in a_list
, so b_list
should be the external loop and a_list
the internal. Also note your sum
variable should be inside the first loop as it is different for every value in b_list
.
If you make this change your code works as expected:
a_list = [['1', 2], ['2', 1], ['1', 1]]
b_list = {'1', '2'}
for j in b_list:
sum = 0
for i in a_list:
if i[0] == j:
sum += i[1]
print(j, sum)
will give your desired output:
('1', 3)
('2', 1)
EDIT: the above solution is a minimal fix to the code posted in the question, however there are more efficient solutions:
Similar to wim's answer, you could use a defaultdictionary, which in this case would be (slightly) more efficient than using the built-in dict
class:
from collections import defaultdict
#
a_list = [['1', 2], ['2', 1], ['1', 1]]
b_list = {'1', '2'}
dict = defaultdict(int)
for key, val in a_list:
if key in b_list:
dict[key] += val
print([[key, dict[key]] for key in b_list])
** credit to coldspeed for the idea for this second solution.