使用map,lambda和函数式编程工作流在Python中映射数组

时间:2018-01-12 21:14:28

标签: python functional-programming

我正在努力理解函数式编程语言是如何工作的,我决定在python中以函数的方式使用程序的方法,因为它是我觉得更舒服的语言。

我正在尝试,给定一个数组数组和一个带有2个参数的函数,在每个数组中得到两个带有两个元素的句子。

我不知道如何在没有嵌套lambda的情况下做到这一点,但即便使用它们:

def sentence( x, y):
    return " this string contains %s and %s" % (x,y)
matrix = [['a','b'],['c','d']]

output = map(lambda a: map(lambda b: map(lambda c,d: sentence(c,d),b),a),matrix)

当然,因为我是一个老式的命令式程序员,所以我尝试用旧的for循环来获得输出。当然有更好的方法,但......

#print(output)
for i in output:
    #print(i)
    for j in i:
        #print(j)
        for k in j:
            print(k)

最后我只得到这个结果:

  File "fp.py", line 12, in <module>
    for k in j:
TypeError: <lambda>() missing 1 required positional argument: 'd'

所以是的,我猜我把错误的值传递给了函数,但是我无法猜到为什么。

有什么想法吗?

5 个答案:

答案 0 :(得分:1)

你做得太难了

def sentence( x, y):
    return " this string contains %s and %s" % (x,y)
matrix = [['a','b'],['c','d']]
# c will get sublists consequently
output = [sentence(*c)  for c in matrix]
print(output) # [' this string contains a and b', ' this string contains c and d']

您可以通过

避免使用上面的代码
output = list(map(lambda c: sentence(*c), matrix))

答案 1 :(得分:0)

你的上一个lambda将不会收到两个参数,因为它会提供b的元素。它必须收到一个论点。

这样的lambdas阶梯在任何语言中看起来都不好看。使用命名函数,它更具可读性。

答案 2 :(得分:0)

你有几个问题,这些结构没有足够深的嵌套来保证嵌套循环。

您希望处理的每个级别的列表都需要1个映射,因此如果要处理列表,则需要映射,如果要处理列表列表,则需要2个等等。

在这种情况下,您很可能只想处理顶级(实际上这是因为您希望顶级中的每个列表都成为句子)。

def sentence( x, y):
return " this string contains %s and %s" % (x,y)
matrix = [['a','b'],['c','d']]

output = map(lambda a: sentence(a[0],a[1]), matrix)

# Print the top level
for i in output:
    print(i)

答案 3 :(得分:0)

  1. Python样式指南推荐using list comprehensions instead of map/reduce
  2. String formatting using percent operator is obsolete,请考虑使用format()方法
  3. 您需要的代码就是这个简单的单行

    输出= [&#34;此字符串包含{}和{}&#34; .format(x,y)for(x,y)in matrix]

答案 4 :(得分:0)

你根本不需要lambdas,但是你需要解压缩你的参数,这些参数在最近的python版本中已经改变了。以下代码适用于较旧版本和较新版本:

def sentence(x_y):
    x, y = x_y
    return "Here is a sentence with {} and {}".format(x, y)

matrix = [['a', 'b'], ['c', 'd']]
output = list(map(sentence, matrix))