温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to find Common Keys in key value Pair which are Less than the Specified Threshold
dictionary loops python keyvaluepair

python - 如何在键值对中找到小于指定阈值的通用键

发布于 2020-03-31 23:44:19

我有一个带有键值对的字典,我想将阈值设置为小于50%的值,这基本上意味着在任何键值对中,值对的值小于所有值的50%,我们应该将该键值对放入在字典中,然后我们在字典中读取了这对,并检查哪些键值正在影响阈值。

{('a','b'):2,('b','c'):4,('c','d'):6,('d','e'):8,('e','f'):8,('f','g'):3,('g','h'):2,('h','i'):7,(i,j):10}

正如你可以在上面dictonary对看(a,b)(b,c)有值2和4,所以在这里我们可以说,由于B是两种常见这就是为什么值小于50%。所以我想打印B中output.Same小于50%如果是(f,g)and (g,h)对,那么这里的输出也是g。

所以我想要的最终输出是-b,g

请帮助我是Python的新手...

查看更多

提问者
Ani
被浏览
170
Chandral 2020-02-01 14:26

这是我解决此问题的方法:

  1. 根据50%的阈值提取所有密钥
  2. 将所有提取的键合并到一个元组中
  3. 提取所有重复的字母(导致值小于阈值的字母)。Set()
def get_my_data(dictionary, threshold):
    if 0 <= threshold <= 100:
        threshold = (max([value for value in dictionary.values()])) * (threshold/100) # Sets threshold value from dictionary values
        merged_keys = ()
        for key, value in dictionary.items():
            if value < threshold:
                merged_keys += key
        return set(letter for letter in merged_keys if merged_keys.count(letter) > 1)
    else:
        return f"Invalid threshold value: {threshold}, please enter a value between 0 to 100."


your_dictionary = {('a', 'b'): 2, ('b', 'c'): 4, ('c', 'd'): 6, ('d', 'e'): 8, ('e', 'f'): 8, ('f', 'g'): 3,
                   ('g', 'h'): 2, ('h', 'i'): 7, ('i', 'j'): 10}
result = get_my_data(your_dictionary, 50)
print(result)

输出量

{'g', 'b'}