列表上的连锁操作(Chainable operations on lists)

我想要做类似的事情

list = [6,4,1,10,8].sort().reverse()

要么

zip([x**2 for x in xrange(5)], [x**3 for x in xrange(5)].reverse()])

但这不起作用,因为列表中的方法不会返回原始对象,所以它们不可链接。

我是否必须使用多行执行此操作,或者是否有一些很酷的函数式编程魔法,我可以在python中通过一行来实现这一点?

I want to do something like

list = [6,4,1,10,8].sort().reverse()

or

zip([x**2 for x in xrange(5)], [x**3 for x in xrange(5)].reverse()])

but this doesn't work because methods on list doesn't return the original object, so they're not chainable.

Do I have to do this using multiple lines or is there some cool functional programming magic I can do in python to achieve this in one line?

最满意答案

你想sorted()和reversed() 。

You want sorted() and reversed().

列表上的连锁操作(Chainable operations on lists)

我想要做类似的事情

list = [6,4,1,10,8].sort().reverse()

要么

zip([x**2 for x in xrange(5)], [x**3 for x in xrange(5)].reverse()])

但这不起作用,因为列表中的方法不会返回原始对象,所以它们不可链接。

我是否必须使用多行执行此操作,或者是否有一些很酷的函数式编程魔法,我可以在python中通过一行来实现这一点?

I want to do something like

list = [6,4,1,10,8].sort().reverse()

or

zip([x**2 for x in xrange(5)], [x**3 for x in xrange(5)].reverse()])

but this doesn't work because methods on list doesn't return the original object, so they're not chainable.

Do I have to do this using multiple lines or is there some cool functional programming magic I can do in python to achieve this in one line?

最满意答案

你想sorted()和reversed() 。

You want sorted() and reversed().