Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using comprehensions to minimize the code. I figured out how to make a comprehension for the list l, but I can't seem to figure out how to make a comprehension for dict d and then transform the two comprehensions to a one-line return statement. Any help would be appreciated!

def f(dct:{str:[(str,int,int)]}) -> [str]:
    d = dict()
    for a,b in dct.items():
        count = 0
        for x,y,z in b:
            if y <= -1:
                y = y * -1
            count += y
        d.update({a:count})
        
    l = list()
    for a,count in sorted(d.items(), key=(lambda t:(-t[1],t[0]))):
        l.append(a)
    return l

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
153 views
Welcome To Ask or Share your Answers For Others

1 Answer

This seems to be the equivalent one liner:

def f2(dct):
    return [a for (a,_) in sorted({a:sum(abs(y) for (_,y,_) in b) for (a,b) in dct.items()}.items(), key=(lambda t:(-t[1],t[0])))]

This version retains the property that items from the original dict which had equivalent sums are sorted in name order.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...