Python summing values in list if it exists in another list

后端 未结 5 537
青春惊慌失措
青春惊慌失措 2021-01-26 11:48

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

5条回答
  •  余生分开走
    2021-01-26 12:17

    Use a dict for grouping:

    d = {}
    for k, v in a_list:
        d[k] = d.get(k, 0) + v
    print([[k, d[k]] for k in b_list])
    

    prints:

    [['2', 1], ['1', 3]]
    

提交回复
热议问题