Python 如何按列表分组?

Python 如何按列表分组?,python,pandas-groupby,Python,Pandas Groupby,例如,如果我们有一个包含很多名字的列表。如何计算序列中出现的次数?或者更确切地说,如何使用groupby对列表进行排序和计数? 就我而言,这个列表不仅仅是['a'、'b'、'c'、'd']。我有60根不同的很长的弦 itertools.groupby是计算序列中出现次数的一个很好的工具 import itertools name_test_random = [**a list of a lot of names**] valdict = dict((k, len(list(g)))

例如,如果我们有一个包含很多名字的列表。如何计算序列中出现的次数?或者更确切地说,如何使用groupby对列表进行排序和计数?
就我而言,这个列表不仅仅是['a'、'b'、'c'、'd']。我有60根不同的很长的弦

itertools.groupby是计算序列中出现次数的一个很好的工具

import itertools
name_test_random = [**a list of a lot of names**]
valdict = dict((k, len(list(g)))
           for k, g in itertools.groupby(name_test_random))
for key, val in valdict.items():
    print(key, ":", val)

使用
集合中的
计数器

l = np.random.choice(list('asdf'), 10)
# array(['f', 's', 's', 'a', 'f', 'a', 'a', 'd', 'd', 'd'], dtype='<U1')

from collections import Counter

Counter(l)
# Counter({'f': 2, 's': 2, 'a': 3, 'd': 3})
l=np.random.choice(列表('asdf'),10)
#数组(['f','s','s','a','f','a','a','d','d','d'],dtype='