How to reduce on a list of tuples in python

后端 未结 4 1541
刺人心
刺人心 2021-01-14 09:50

I have an array and I want to count the occurrence of each item in the array.

I have managed to use a map function to produce a list of tuples.

def         


        
4条回答
  •  囚心锁ツ
    2021-01-14 10:35

    If all you need is cnt, then a dict would probably be better than a list of tuples here (if you need this format, just use dict.items).

    The collections module has a useful data structure for this, a defaultdict.

    from collections import defaultdict
    cnt = defaultdict(int) # create a default dict where the default value is
                           # the result of calling int
    for key in arr:
      cnt[key] += 1 # if key is not in cnt, it will put in the default
    
    # cnt_list = list(cnt.items())
    

提交回复
热议问题