简体   繁体   English

将序列转换为列表的功能

[英]Function that turns sequence into list

We know that 我们知道

list(map(f,[1,2],[3,4],[6,7]))

is equivalent to 相当于

[f(1,3,6),f(2,4,7)]

I want to know if there is built-in function tolist that is equivalent to [] , so that 我想知道是否有等效于[]内置函数tolist

tolist(a,b,c,d)

is equivalent to [a,b,c,d] . 等价于[a,b,c,d]

I think such a function is useful in functional programming. 我认为这样的功能在函数式编程中很有用。 Because many functions take list parameter instead of sequence. 因为许多函数采用列表参数而不是序列。

Of course, a simple custom way is lambda *x:list(x) , but I always feels it is syntactically cumbersome, especially use it in functional programming style like 当然,一种简单的自定义方式是lambda *x:list(x) ,但是我一直觉得它在语法上很麻烦,尤其是在像下面这样的函数式编程风格中使用它

map(lambda *x:list(x),[1,2],[3,4],[6,7])

So my question is that if there is no such built-in tolist , whether we could build it on the fly more elegantly using FP packages like toolz ? 所以我的问题是,如果没有这样的内置tolist ,是否可以使用诸如toolz类的FP软件包更优雅地动态构建它?

PS: What I actually want to achieve is threaded version of add (I know numpy, but I don't want to use it at the moment) PS:我真正想要实现的是add的线程版本(我知道numpy,但目前不想使用它)

from toolz.curried import *
import operator as op
def addwise(*args):
    return list(map(compose(reduce(op.add),lambda *x:list(x)),*args))

then 然后

addwise([1,2],[3,4],[6,7])

will gives 将给

[10, 13]

If 如果

function is useful (....) Because many functions take list parameter 函数很有用(....),因为许多函数采用list参数

it is a good sign that lambda expression is not a right fit. 这是lambda表达式不合适的一个好兆头。 You don't want to repeat yourself every time you want to apply this pattern. 您不想每次都想重复使用此模式。

Sadly we are far from Clojure conciseness: 可悲的是,我们离Clojure的简洁还很远:

user=> (map + [1 2] [3 4] [6 7])
(10 13)

but we can still express it in a fairly Pythonic and elegant way: 但是我们仍然可以用相当Python化和优雅的方式来表达它:

def apply(f):
    def _(*args):
        return f(args)
    return _ 

which can be used as: 可以用作:

from toolz.curried import reduce 

map(apply(reduce(op.add)), [1,2], [3,4], [6,7])

or even better 甚至更好

map(apply(sum), [1,2], [3,4], [6,7])

although in this case map , can be combined with zip : 尽管在这种情况下map可以与zip结合使用:

map(sum, zip([1, 2], [3, 4], [6, 7])))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM