【问题标题】:Lambda if else statements returning True when argument equal to 1当参数等于 1 时,Lambda if else 语句返回 True
【发布时间】:2021-01-15 21:48:38
【问题描述】:

我正在努力调试我的代码,我认为我面临的问题是,当参数中包含 1 时,无论它是否是正确的键,它都会返回为 True。有没有办法阻止这种情况发生?

def reduce_search(L, x): #L is a list, and x is the key to find in the list
    #FIX
    return reduce(lambda y,z: True if (y == True or z == True) else (True if (y == x or z == x) else False), False, L) #NOTE: not using the imported reduce method

def test_reduce_search():
    assert reduce_search([1, 3, 5, 4, 2, 9, 7], 2) == (2 in [1, 3, 5, 4, 2, 9, 7]) #return true
    assert reduce_search([1, 3, 5, 2, 9, 7], 99) == (99 in [1, 3, 5, 4, 2, 9, 7]) #return false

【问题讨论】:

  • “不使用导入的reduce方法”是什么意思?你用的是哪个reduce?哪里来的?

标签: python search lambda boolean reduce


【解决方案1】:

因为1 == True

我想你只是想要:

from functools import reduce
def reduce_search(L, x):
    return reduce(lambda acc, item: item == x or acc, L, False)

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 2016-09-03
    • 2021-08-31
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多