Python summing values in list if it exists in another list

后端 未结 5 530
青春惊慌失措
青春惊慌失措 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:18

    Accumulate numbers using a dict, and then gather the results using a list comprehension:

    >>> d = dict.fromkeys(b_list, 0)
    >>> for k, n in a_list: 
    ...     if k in d: 
    ...         d[k] += n 
    ...
    >>> [[k, n] for k, n in d.items()]
    [['1', 3], ['2', 1]]
    

提交回复
热议问题