2024-09-28 17:19:55 发布
网友
我试图以OrderedCounter输出中显示的相同顺序打印出键值对。在
from collections import Counter, OrderedDict class OrderedCounter(Counter, OrderedDict): pass c = OrderedCounter('supernatural') print c
我得到以下输出:
有没有办法只打印出第一个键,值对?在
我基本上是想打印给定字符串中的第一个重复字符。在
据我所知,我认为你正在寻找这样的东西:
print c.most_common()[0]
这将产生输出('u', 2)
('u', 2)
问题是第一个超类使用了__repr__(因为您没有重写它),这就是Counter。Counter的表示方式是按值的降序排序。子类OrderedDict和sorted是稳定的,这使得{}似乎是第一个元素。在
__repr__
Counter
OrderedDict
sorted
但是Counter不提供__iter__方法,因此您将使用OrderedDict的__iter__,它只是保持插入顺序:
__iter__
>>> next(iter(c.items())) ('s', 1)
要获得第一个重复的字符,只需使用理解:
(对于Python2,您可能希望使用iteritems()而不是{})
iteritems()
要打印第一个最常见的值,可以使用Counter.most_common方法:
Counter.most_common
>>> c.most_common(1) [('u', 2)]
此任务不需要Count或{}。下面是一个优化的方法(对于长度为n的字符串,复杂性为O(n)):
Count
n
In [35]: def first_repeated(s): seen = set() for i, j in enumerate(s): if j in seen: # membership check in set is O(1) return j, s.count(j, i + 1) + 2 seen.add(j) ....: In [36]: first_repeated(s) Out[36]: ('u', 2)
下面是一个带有其他答案的基准测试,它显示此方法几乎快4-5倍:
此外,如果您想对大量数据执行此任务,则可以使用suffix tree更快地完成此任务。下面是我自己在github中对该算法的优化实现。如果您不熟悉这种数据结构和算法https://github.com/kasramvd/SuffixTree,也可以使用文档和有用的链接
作为在生成器表达式中使用str.counter的另一个基于线性的答案,您可以使用@Stefan Pochmann建议的以下方法:
str.counter
next((c, s.count(c)) for c in s if s.count(c) > 1)
据我所知,我认为你正在寻找这样的东西:
这将产生输出
('u', 2)
问题是第一个超类使用了}似乎是第一个元素。在
__repr__
(因为您没有重写它),这就是Counter
。Counter
的表示方式是按值的降序排序。子类OrderedDict
和sorted
是稳定的,这使得{但是
Counter
不提供__iter__
方法,因此您将使用OrderedDict
的__iter__
,它只是保持插入顺序:要获得第一个重复的字符,只需使用理解:
^{pr2}$(对于Python2,您可能希望使用})
iteritems()
而不是{要打印第一个最常见的值,可以使用
Counter.most_common
方法:此任务不需要}。下面是一个优化的方法(对于长度为
Count
或{n
的字符串,复杂性为O(n)):下面是一个带有其他答案的基准测试,它显示此方法几乎快4-5倍:
^{pr2}$此外,如果您想对大量数据执行此任务,则可以使用suffix tree更快地完成此任务。下面是我自己在github中对该算法的优化实现。如果您不熟悉这种数据结构和算法https://github.com/kasramvd/SuffixTree,也可以使用文档和有用的链接
作为在生成器表达式中使用
str.counter
的另一个基于线性的答案,您可以使用@Stefan Pochmann建议的以下方法:相关问题 更多 >
编程相关推荐