How to get unique values with respective occurrence count from a list in Python?

前端 未结 11 2060
孤独总比滥情好
孤独总比滥情好 2020-12-13 13:13

I have a list which has repeating items and I want a list of the unique items with their frequency.

For example, I have [\'a\', \'a\', \'b\', \'b\', \'b\']

11条回答
  •  天命终不由人
    2020-12-13 13:58

    Another way to do this would be

    mylist = [1, 1, 2, 3, 3, 3, 4, 4, 4, 4]
    mydict = {}
    for i in mylist:
        if i in mydict: mydict[i] += 1
        else: mydict[i] = 1
    

    then to get the list of tuples,

    mytups = [(i, mydict[i]) for i in mydict]
    

    This only goes over the list once, but it does have to traverse the dictionary once as well. However, given that there are a lot of duplicates in the list, then the dictionary should be a lot smaller, hence faster to traverse.

    Nevertheless, not a very pretty or concise bit of code, I'll admit.

提交回复
热议问题