Python summing values in list if it exists in another list

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

    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)
    

提交回复
热议问题