Qiang Li
Qiang Li

Reputation: 10865

Any way to shorten statements in python

I want to get do the following (after annoyed by the methods in python which do not seem to return the original object):

take the values out of a dictionary d, and sort it in reverse order

values=d.values()
values.sort(reverse=True)

But is there a way to shorten it to one line? In general, I also want to do:

weight=range(1,27)
weight.reverse()

(I of course could use range(26,0,-1), but if I stick to what I wrote above, is there a way to do it like weight=range(1,27).reverse()?)

Upvotes: 0

Views: 97

Answers (3)

Platinum Azure
Platinum Azure

Reputation: 46203

Usually, mutating methods in Python return None.

There are some built-ins useful to you in this particular case:

weight = list(reversed(range(1,27)))

The reversed and sorted builtins return new lists, so you can keep using the old one if you want.

Upvotes: 0

PaulMcG
PaulMcG

Reputation: 63762

Use builtins sorted and reversed:

values = sorted(d.values, reverse=True)

weight = reversed(range(1,27))

Upvotes: 0

Keith
Keith

Reputation: 43054

You can use the sorted function:

rvals = sorted(d.values(), reverse=True)

Upvotes: 3

Related Questions