【发布时间】:2020-08-29 15:16:30
【问题描述】:
我在使用这种 lambdas 语法时遇到了问题。 我正在尝试将布尔值列表转换为整数值,但出现错误,我不明白为什么。
代码如下:
from functools import reduce
binary = [True, True, False, True]
L = list(range(len(binary))) #Step 1
print(L) #[0, 1, 2, 3]
L = map(lambda a: 2**a, L) #Step 2
print(L) #[1, 2, 4, 8]
L = zip(binary, L) #Step 3
print(L) #[(True, 1),(True, 2),(False, 4),(True, 8)]
L = filter(lambda a, b: a, L) #Step 4
print(L) #[(True, 1),(True, 2),(True, 8)] not sure
L = map(lambda a, b: b, L) #Step 5
print(L) #?????
L = reduce(lambda a, b: a + b, L) #Final step
print(L) #11
输出:
Traceback (most recent call last):
File "C:/Users/axel_/PycharmProjects/Python_Subject_Exam/19_new_exam_binary_list_translation.py", line 27, in <module>
L = reduce(lambda a, b: a + b, L)
TypeError: <lambda>() missing 1 required positional argument: 'b'
[0, 1, 2, 3]
<map object at 0x00000267FAFE5388>
<zip object at 0x00000267FAFE50C8>
<filter object at 0x00000267FAFE5248>
<map object at 0x00000267FAFE4EC8>
Process finished with exit code 1
谁能帮我调试一下?
【问题讨论】:
-
map和reduce在 python3 中返回一个生成器。所以,你只需要在打印时将L转换为list......就像这样:print( list(L) ) -
知道了@Anwarvic 感谢您的回复,但我仍然在想为什么我不能执行
reduce -
如果您遵循@Anwarvic 的建议,您将能够在调用 reduce 之前看到输出。这可能会帮助您确定您的问题。
-
您的错误在这里
L = filter(lambda a, b: a, L)过滤器采用带有 single 参数的 lambda。更好的选择是将其表示为L = (b for a, b in L if a)这是filter的生成器表达式版本。 -
使用生成器表达式实际上可以将整个操作简化为
sum(2**i for i, b in enumerate(binary) if b)
标签: python lambda filter boolean reduce