简体   繁体   中英

Is there array_count_values() analogue for Python 3.x or best way to do this?

Is there array_count_values() analogue or fastest way to do this in Python 3.x

from

d = ["1", "this", "1", "is", "Sparta", "Sparta"]

to

{
  '1': 2,
  'this': 1,
  'is': 1,
  'Sparta': 2
}

You can count the occurrence of each element in a list using Counter :

from collections import Counter

l = [1, "this", 1, "is", "Sparta", "Sparta"]
print(Counter(l))

This prints

Counter({1: 2, 'Sparta': 2, 'this': 1, 'is': 1})

repl.it link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM