Counting the amount of occurrences in a list of tuples

后端 未结 3 1834
余生分开走
余生分开走 2021-02-04 01:44

I am fairly new to python, but I haven\'t been able to find a solution to my problem anywhere.

I want to count the occurrences of a string inside a list of tuples.

3条回答
  •  失恋的感觉
    2021-02-04 01:58

    I needed some extra functionality that Counter didn't have. I have a list of tuples that the first element is the key and the second element is the amount to add. @jamylak solution was a great adaptation for this!

    >>> list = [(0,5), (3,2), (2,1), (0,2), (3,4)]
    
    >>> d = {}
    >>> for x, y in list1:
        d[x] = d.get(x, 0) + y
    
    >>> d
    {0: 7, 2: 1, 3: 6}
    

提交回复
热议问题