gpt4 book ai didi

Python 计数器 : print key whose count is x

转载 作者:太空宇宙 更新时间:2023-11-03 12:39:36 26 4
gpt4 key购买 nike

假设我有一个代表单词集合的 Counter 对象:

>>> words = ['hello', 'hello', 'hello', 'world']
>>> counter = Counter(words)

找出哪些词的计数为 1 的一种方法是遍历 counter:

for word, count in counter.items():
if count == 1:
print(word)

有没有更简单/更好的方法来做到这一点?也就是说,是否可以“反转”counter 以给出计数为 x 的单词?

最佳答案

要反转任何映射——无论是 Counterdict 还是其他任何东西:

rev = {v: k for k, v in d.items()}

然后您可以像使用任何其他词典一样使用它:

key_whose_count_is_10 = rev[10]

在有两个具有相同值的键的情况下,该值将任意映射到其中一个。但这在你的问题中几乎是固有的。您正在请求计数为 x 的“the”键;如果有三个键的个数是x,你想做什么?


如果您只打算进行一次查询,而不是多次查询,则迭代会更有效。哪一个更更清楚(这几乎总是更重要)是有争议的。这是一种方法,用于比较:

key_whose_count_is_10 = next(k for k, v in d.items() if v==10)

关于Python 计数器 : print key whose count is x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25275362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com