Combine methods in Python, like in Ruby

In Ruby, you can combine methods as follows:

a = [2,3,1]
b = a.sort.reverse

which sets the value of the variable bto [3,2,1], leaving athe same.

I would like to perform similar operations in Python. So far the shortest way to do this, I have found:

import copy
a = [2,3,1]
b = copy.copy(a)
b.sort()
b.reverse()

That is, with 5 lines of code instead of 2. Is there an easier way?

+4
source share
2 answers

Clarification: the original answer is given below. As noted, the question lies in the chain as a whole, and not in any particular case. A clarification of this can be found at the end of this answer.


You can spell it right straight.

a = [2,3,1]
b = sorted(a, reverse=True)

Even if you want to use only methods, you can do it quite simply:

a = [2,3,1]
b = a.copy()  # a[:] in python2
b.sort(reverse=True)

Python . , . python , , ( ) . , .


python. , , ( ).

, .

foo = they.method.method.method()
foo = my_func(your_func(their_func()))

[2,3,1].sort().reverse(). :

a = [2,3,1]
b = a.sort()
c = b.reverse()

s.sort() None, None.reverse() - None.

. , - . ,

s = "ab:cd".upper().center(20).partition(':')
print(s)

(' AB', ':', 'CD ').

+4

. , :-).

a = [2,3,1]
[eval('a.'+f+'()') for f in ['sort', 'reverse']]

, , .

0

All Articles