简体   繁体   English

搜索字典中的键的值是否为2或更大

[英]searching if a key in a dictionary has a value of 2 or greater

The function histogram returns a dictionary where the keys are letters and the values are the number of times that letter appears in the argument passed to it. 函数直方图返回一个字典,其中的键是字母,值是字母在传递给它的参数中出现的次数。

def histogram(s):
    d = dict()
        for c in s:
            if c not in d:
                d[c] = 1
            else:
                d[c] += 1
    return d

I would like the function has_duplicates to use histogram. 我希望函数has_duplicates使用直方图。 Then search the dictionary that is returned to check for any values that are greater than 1, returning either True or False . 然后搜索返回的字典以检查任何大于1的值,并返回TrueFalse

def has_duplicates(t):
     histogram(t)

I am having difficulty accessing the values within the dictionary that's been returned by histogram. 我很难访问直方图返回的字典中的值。

  • You are not assigning histogram(t) to anything in your has_duplicates function. 您没有在has_duplicates函数中分配任何histogram(t)

  • You don't need to reinvent a wheel: collections.Counter will do it for you. 您不需要重新发明轮子: collections.Counter 。Counter会为您完成。

So... something like this? 所以...这样的事情?

from collections import Counter

def has_duplicates(s):
    counter = Counter(s)
    return {key: value > 1 for key, value in counter.items()}

has_duplicates([1, 2, 7, 2, 2])
# => {1: False, 2: True, 7: False}

If you meant a single True if any duplicates are detected, 如果您的意思是如果检测到任何重复,则为True

def has_duplicates(s):
    counter = Counter(s)
    return any(value > 1 for value in counter.values())

has_duplicates([1, 2, 7, 2, 2])
# => True

like so: 像这样:

def has_duplicates(t):
   d = histogram(t)
   duplicates = [key for key, value in d.items() if value > 1]
   return True if duplicates else False
   # or just: return bool(duplicates)

Assuming its python 3 假设它的python 3

s = {"a": 1, "b":3, "c":2, "d":4, "e":1}

s_new = {k:v for k,v in s.items() if v > 1}

print(s_new)

Result: 结果:

{'d': 4, 'b': 3, 'c': 2} {'d':4,'b':3,'c':2}

For Python 2, use iteritems() 对于Python 2,请使用iteritems()

If you're only interested in whether or not there are duplicates, there is no reason to loop over the entire dictionary when you've found a duplicate earlier: 如果您只对是否存在重复感兴趣,那么当您较早地发现重复时,没有理由遍历整个字典:

def has_duplicates(t):
    for v in t.values():
        if v > 1:
            return True
    return False

collections.Counter however is useful for counting the characters in histogram() . 但是collections.Counter对于计数histogram()的字符很有用。

You find good answers to your question in the posts, above. 您可以在上面的帖子中找到问题的良好答案。

But here's another approach with little code that you might think about, if your goal is just to check for any duplicate characters (or objects): 但是,如果您的目标只是检查是否有重复的字符(或对象),那么这是您可能会想到的很少代码的另一种方法:

def has_dupes(t):
    return len(t) != len(set(t))

set(t) converts the string in t into a set of chars. 集(t)的 T中的字符串转换成一组字符的。 During conversion, all duplicates are automatically removed, because sets can hold every object only once. 在转换过程中,所有重复项都会自动删除,因为集合只能将每个对象容纳一次。 Comparing the length of the initial string with the number of items in the created set will return True if there are no duplicates, but False if at least one duplicate has been removed during set creation. 如果没有重复项,则将初始字符串的长度与创建的集合中的项目数进行比较将返回True,但是如果在集合创建过程中删除了至少一个重复项,则返回False。 That works with other sequences as well. 这也适用于其他序列。

Note: Negative comparison '!=' was used to make the function a positive check for dupes, instead of a negative check for no dupes. 注意:负比较'!='用于使函数对重复项进行正检查,而不是对不重复项进行负检查。

Michael 麦可

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM