【问题标题】:Optimizing the Nested dictionary in python problem优化python问题中的嵌套字典
【发布时间】:2022-01-22 20:35:50
【问题描述】:

如果一个接收者在每个类别中拥有最多,你必须返回他的名字。如果没有所有类别中值最多的接收者,则应返回“无”。

receivers = ({'abdul': {'a': 1800, 'b': 18, 'c': 117},
              'ahmed' :  {'a': 1700, 'b': 17, 'c': 116},
              'rehman' : {'a': 1750,'b': 16, 'c': 113}})
     
def triple_crown(receivers):
aa= [j['a'] for i,j in l.items()]
bb= [j['b'] for i,j in l.items()]
cc= [j['c'] for i,j in l.items()]
p = ['abdul', 'ahmed', 'rehman']
for i,j in enumerate(list(zip(aa,bb,cc))):
    x,y,z=j
    if x==max(aa) and aa.count(x)==1:
        if y==max(bb) and bb.count(y)==1:
            if z==max(cc) and cc.count(z)==1:
                return p[i]
else:
    return 'None of them'

输出应该是“abdul”,因为他的 a、b 和 c 值比他的同行多

我以这种方式定义了函数,但我想应该有更好的方法来做到这一点,因为这是一个非常糟糕的解决方案

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    这是一种方法:

    首先,遍历receivers 和内部字典,根据所有内部字典的最大值创建字典max_dct

    然后,检查max_dct是否存在于receivers中,如果存在则查找对应的key,如果不存在则打印“None”

    max_dct = {}
    for name, dct in receivers.items():
        for k,v in dct.items():
            max_dct[k] = max_dct[k] if k in max_dct and max_dct[k] > v else v
    
    out = None
    for name, dct in receivers.items():
        common_vals = set(max_dct.values()) & set(dct.values())
        if common_vals:
            if len(common_vals) == len(max_dct):
                out = name
            break
            
    out = out if out is not None else 'None of them'
    print(out)
    

    输出:

    abdul
    

    【讨论】:

    • 优秀的解决方案!然而,有一个问题是,对于两个玩家得分相同的情况,它不应该返回任何一个。但它却认为它是最好的
    • receivers = ({'abdul': {'a': 1800, 'b': 16, 'c': 117}, 'ahmed' : {'a': 1700, 'b' : 17, 'c': 116}, 'rehman' : {'a': 1800,'b': 16, 'c': 200}}) 例如对于这个 dic 输出是 'rehman' 但它应该是他们都没有。即使是你更新的
    • receivers = ({'abdul': {'a': 1800, 'b': 16, 'c': 110}, 'ahmed' : {'a': 1700, 'b' : 15, 'c': 112}, 'rehman' : {'a': 1800,'b': 16, 'c': 113}}) 是的,你是对的,但是当我改变这个值时,例如它会输出 'rehman' 而不是一个都没有
    • @abdulrehman 所以你抛出名字的唯一情况是当所有三个值都更大时?
    • 是的,所有值都应该更大。我让您的解决方案遍历内部 dict 并保存最大值,然后将其与 dict 进行比较,以查看 max dict 和接收器之间是否存在匹配。但如果值相等。我无法理解如何应对它
    猜你喜欢
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多