Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

python - How to turn code into one-line return statement

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...