在 Python 3.x 中是否有 array_count_values() 类似物或最快的方法
从
d = ["1", "this", "1", "is", "Sparta", "Sparta"]
Run Code Online (Sandbox Code Playgroud)
到
{
'1': 2,
'this': 1,
'is': 1,
'Sparta': 2
}
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方法计算列表中每个元素的出现次数Counter:
from collections import Counter
l = [1, "this", 1, "is", "Sparta", "Sparta"]
print(Counter(l))
Run Code Online (Sandbox Code Playgroud)
这打印
Counter({1: 2, 'Sparta': 2, 'this': 1, 'is': 1})
Run Code Online (Sandbox Code Playgroud)