[英]lambda function within map function with if but without else statement in Python
[英]Python if else statement not working in reduce lambda function
我是新来lambda
和reduce
在Python,我不明白为什么这个功能不工作:
def my_func(str):
symbols = ['_', '-']
return reduce(lambda x, y: ' ' + y if x in symbols else x + y, str)
my_func('foo_bar-baz') # 'foo_bar-baz'
我预计输出为'foo bar baz'
。
有谁明白这里有什么问题?
您似乎对reduce
的函数参数的参数顺序感到困惑。 第一个参数是运行总数,第二个参数是新数据。 在您的示例中, x
是内置字符串, y
是新字符。
尝试这个:
def my_func(str):
symbols = ['_', '-']
return reduce(lambda x, y: x + (' ' if y in symbols else y), str)
print my_func('foo_bar-baz') # 'foo bar baz'
注意这里的错误:在第一次调用 lambda 表达式时, x
是str[0]
,而y
是str[1]
。 因此,如果传入字符串中的第一个字符是符号,则不会对其进行翻译。
print my_func('-foo_bar-baz')
-foo bar baz
这可以通过为reduce()
提供第三个参数来解决:
def my_func(str):
symbols = ['_', '-']
return reduce(lambda x, y: x + (' ' if y in symbols else y), str, '')
print my_func('foo_bar-baz') # 'foo bar baz'
print my_func('-foo_bar-baz') # ' foo bar baz'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.