使用 lambda 减少列表

Reduce a list using lambda

我需要写几个这样的函数。有没有更好的方法在一行左右使用 lambda 编写此函数。

def is_digital(offers):
    for offer in offers:
        digital = True if 'digital' in offer and offer['digital'] else False
        if digital:
            return True
    return False

你可以只使用 any

def is_digital(offers):
    return any(offer.get('digital') for offer in offers)

或者如果您想删除完整的函数定义并只使用 lambda(不是最好的主意),您可以这样做:

is_digital = lambda offers: any(offer.get('digital') for offer in offers)

感谢 jonrsharpe 的评论提醒我 .get 是一回事。

至于我下面的检查方式更具可读性和明确性:

def is_digital(offers):
    return any(map(lambda x: x.get('digital', False), offers))

您甚至可以丢弃默认值 'False',因为如果没有找到指定的键,'None' 就是默认值 return。但我认为代码会变得不那么明确。

def is_digital(offers):
    return any(map(lambda x: x.get('digital'), offers))

选择权在你。 =)