使用python map等功能工具 [英] Using python map and other functional tools
问题描述
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,
def maptest(foo,bar):
print foo,bar
map(maptest,foos,bars)
产生:
1.0 1
2.0 2
3.0 3
4.0无
5.0无
Q。有没有办法在python中使用地图或其他任何功能工具来生成以下的无循环等。
1.0 [1,2,3]
2.0 [1,2,3]
3.0 [1,2,3]
4.0 [1,2,3]
5.0 [ 1,2,3]
正如一个附注说明如何实现改变如果有是foo和bar之间的依赖关系。例如
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1 ,2,3,4,5]
并打印:
1.0 [2,3,4,5]
2.0 [1,3,4,5]
3.0 [1,2,4,5]
...
PS :我知道如何天真地使用if,循环和/或生成器,但我想学习如何使用功能工具来实现相同的功能。是否只是在maptest中添加一个if语句来映射测试或应用另一个过滤器映射到内部吧?
p>最简单的方法是不要通过不同的函数通过 bar
,而是直接从 maptest
访问它:
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo):
print foo,bars
map(maptest,foos)
使用您原来的 maptest
函数,您还可以在 map
map((lambda foo:maptest(foo,bars)),foos)
This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo, bar):
print foo, bar
map(maptest, foos, bars)
produces:
1.0 1
2.0 2
3.0 3
4.0 None
5.0 None
Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.
1.0 [1,2,3]
2.0 [1,2,3]
3.0 [1,2,3]
4.0 [1,2,3]
5.0 [1,2,3]
Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3,4,5]
and print:
1.0 [2,3,4,5]
2.0 [1,3,4,5]
3.0 [1,2,4,5]
...
P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?
The easiest way would be not to pass bars
through the different functions, but to access it directly from maptest
:
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo):
print foo, bars
map(maptest, foos)
With your original maptest
function you could also use a lambda function in map
:
map((lambda foo: maptest(foo, bars)), foos)
这篇关于使用python map等功能工具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!