所以我有一个字符串列表:
list1 = ["1thing", "2thing", "3thing", "1thing"]
我想知道每个人在列表中的次数。问题是,我只想比较前两个字符,因为我知道如果第一个字符说3个字符是相同的,那么整个字符串是相同的。我在想我可以修改内置的list.count(x)方法,或者我可以覆盖__eq__
运算符,但我不知道如何做其中任何一个。
答案 0 :(得分:8)
使用生成器提取前几个字符,并使用内置的collections.Counter
类:
Counter(item[:2] for item in list1)
答案 1 :(得分:5)
为什么要经历所有的麻烦......使用collections.Counter
模块来查找频率。
>>> import collections
>>> x=['1thing', '2thing', '1thing', '3thing']
>>> y=collections.Counter(x)
>>> y
Counter({'1thing': 2, '2thing': 1, '3thing': 1})
答案 2 :(得分:1)
可能不如@ Marcin的解决方案那么好,但使用itertools.groupby
可能会使其更具可读性和灵活性。
from itertools import groupby
def group_by_startswith(it, n):
"""Get a dict mapping the first n characters to the number of matches."""
def first_n(str_):
return str_[:n]
startswith_sorted = sorted(it, key=first_n)
groups = groupby(startswith_sorted, key=first_n)
return {key: len(list(grouped)) for key, grouped in groups}
示例输出:
>>> list1 = ["1thing", "2thing", "3thing", "1thing"]
>>> print(group_by_startswith(list1, 3))
{'3th': 1, '2th': 1, '1th': 2}
此解决方案可让您在结果上获得更多灵活性。例如,修改返回行以返回grouped
或list(grouped)
可以轻松获取匹配的对象。