【问题标题】:Filter out entries in dictionary based on the sum of the keys根据键的总和过滤掉字典中的条目
【发布时间】:2018-04-20 09:57:29
【问题描述】:
# given I want to find the x largest,

dictionary = {'cat': (3,4,5), 'meow': (6,4,1), 'dog': (1,2,3)}
x = list(dictionary.values())
lst = []
for i in x:
    lst.append(sum(i))
for num in range (x-1):
    final = (filter(lambda x: sum(x.key()) == lst[num] , dictionary)
print(final)

# expected answer (if x = 1):
{"cat": (3,4,5)} 
#because it has the largest sum (3+4+5)

这是我到目前为止所得到的,但是我在扫描字符串文字错误时遇到了 EOL,这意味着我什至无法测试它是否正确。

编辑:刚刚尝试了另一种方法,这似乎更简洁。但是,如何让它循环整个字典呢?

def wrtd2(s):
    dictionary = {}
    for val in s:
        x = max(list(s.items()), key = lambda x: sum(x[1]))
        if x[0] not in dictionary:
            dictionary[x[0]] = x[1]
    return dictionary

【问题讨论】:

  • 你在final =线上的括号不均匀......无论如何你想要max(dictionary.items(), key = lambda x: sum(x[1]))
  • 在这种情况下 max 会起作用,因为碰巧我的 x 是 1。如果我想找到超过 1 怎么办?
  • 啊,是的,在这种情况下使用相同的键功能,但结帐heapq.nlargest() 或只是sorted(),然后通过切片获取第一个x 项目
  • 嘿,非常感谢。我实际上检查了您为副本发送的链接,我喜欢里面的解决方案。但是有一个问题。使用 max 函数,它只循环一次并找到最大值。但我希望它继续循环,直到返回一个排序的字典。介意分享一些关于如何做到这一点的想法吗?我将在问题中发布代码。
  • sorted(dictionary.items(), key = lambda x: sum(x[1]))

标签: python dictionary


【解决方案1】:

您还可以使用maxmap 来检索最大值和。

然后通过字典理解过滤您的字典。

d = {'cat': (3,4,5), 'meow': (6,4,1), 'dog': (1,2,3)}

maxval = max(map(sum, d.values()))

res = {k: v for k, v in d.items() if sum(v) == maxval}

# {'cat': (3, 4, 5)}

【讨论】:

    猜你喜欢
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多