【问题标题】:What is the correct lambda for the following projecting function? [duplicate]以下投影函数的正确 lambda 是多少? [复制]
【发布时间】:2021-12-25 20:22:08
【问题描述】:

以下代码无法编译。

data = [5, 3, 2, 4, 1]   

def projector(x):
    if (x % 2) == 0:
        return 1
    else:
        return 0    

# evens = map(projector, data)
evens = map(lambda x: if (x % 2) == 0: 1 else: 0, data)
print(list(evens))

问题

与上述projector 等效的正确 lambda 是什么?

【问题讨论】:

标签: python


【解决方案1】:

见ternary operators

你想要:

res = 0 if (x % 2) == 0 else 1

你可以这样映射:

evens = map(lambda x: 0 if (x % 2) == 0 else 1, data)

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2015-12-01
    • 2022-11-22
    相关资源
    最近更新 更多