打印第一个有序计数中的键值

2024-09-28 17:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图以OrderedCounter输出中显示的相同顺序打印出键值对。在

from collections import Counter, OrderedDict

class OrderedCounter(Counter, OrderedDict):
    pass

c = OrderedCounter('supernatural')
print c

我得到以下输出:

^{pr2}$

有没有办法只打印出第一个键,值对?在

我基本上是想打印给定字符串中的第一个重复字符。在


Tags: 字符串fromimport顺序counterpasscollectionsclass
3条回答

据我所知,我认为你正在寻找这样的东西:

print c.most_common()[0]

这将产生输出('u', 2)

问题是第一个超类使用了__repr__(因为您没有重写它),这就是CounterCounter的表示方式是按值的降序排序。子类OrderedDictsorted是稳定的,这使得{}似乎是第一个元素。在

但是Counter不提供__iter__方法,因此您将使用OrderedDict__iter__,它只是保持插入顺序:

>>> next(iter(c.items()))
('s', 1)

要获得第一个重复的字符,只需使用理解:

^{pr2}$

(对于Python2,您可能希望使用iteritems()而不是{})

要打印第一个最常见的值,可以使用Counter.most_common方法:

>>> c.most_common(1)
[('u', 2)]

此任务不需要Count或{}。下面是一个优化的方法(对于长度为n的字符串,复杂性为O(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倍:

^{pr2}$

此外,如果您想对大量数据执行此任务,则可以使用suffix tree更快地完成此任务。下面是我自己在github中对该算法的优化实现。如果您不熟悉这种数据结构和算法https://github.com/kasramvd/SuffixTree,也可以使用文档和有用的链接

作为在生成器表达式中使用str.counter的另一个基于线性的答案,您可以使用@Stefan Pochmann建议的以下方法:

next((c, s.count(c)) for c in s if s.count(c) > 1)

相关问题 更多 >