简体   繁体   English

如何从python中的lambda获取布尔值?

[英]How to get boolean values from lambda in python?

I am trying to feed values into lambda and if values exceed a certain limit consecutively 5 times I want to return 1 from the function, I am using filter but each time the if statement executes. 我试图将值输入到lambda中,并且如果值连续超过5次超出某个限制,我想从该函数返回1,则我使用过滤器,但是每次执行if语句时。 How should I implement it using lambda? 我应该如何使用lambda实现它? Please any other suggestion. 请提出任何其他建议。

rpm = [45,20,30,50,52,35,55,65]
rpm_limit=45

def check():
    x, i = 0, 0 
    while i < len(rpm):
        if (filter(lambda x: x > rpm_limit, rpm)): # rpm values will be feeded continuously
            x=x+1
            print("RPM: ",rpm[i])
            if x >= 5:
                return 1
            else:
                x=0
        i += 1
    return 0    

print(check())

If you're dead set on using a lambda expression, I think reduce is better suited to your purposes. 如果您不愿意使用lambda表达式,那么我认为reduce会更适合您的目的。

def check():
    max_consec = reduce(lambda acc, r: acc + 1 if r > rpm_limit else 0, rpm, 0)
    return 1 if max_consec >= 5 else 0

Here's what's going on: acc gets incremented every time an rpm exceeds the max and set to 0 whenever it doesn't. 这是怎么回事:每次转速超过最大值时, acc就会增加,而每当转速未达到最大值时, acc就会设置为0。 This gives us the longest streak of over-the-max rpms, which we use to decide if we return a 1 or a 0. 这为我们提供了最长的最大rpm条纹,我们可以用来确定是否返回1或0。

demo 演示

EDIT: for python 3, you'll need to import reduce from functools . 编辑:对于python 3,您需要从functools导入reduce See demo for example. 例如,请参见演示。

EDIT2: Corrected some faulty logic. EDIT2:更正了一些错误的逻辑。 In this new example, acc will contiune to be incremented if the max streak length has been met, so the end predicate is true whenever the max streak length has been exceeded. 在此新示例中,如果已达到最大条纹长度,则acc将继续递增,因此只要超过最大条纹长度,则结束谓词为true。 See demo link above for live example. 有关实际示例,请参见上面的演示链接。

def check():
    max_consec = reduce(
      lambda acc, r: acc + 1 if (r > rpm_limit or acc >= max_streak) else 0, rpm, 0)
    return 1 if max_consec >= max_streak else 0

Isn't that what you want ? 那不是你想要的吗? Without filter and lambda, you could create a new list of 0/1 (1 if the limit is exceeded). 如果没有filter和lambda,则可以创建一个新列表0/1(如果超出限制,则为1)。 After that you simply need to sum it up: 之后,您只需要总结一下:

rpm = [45,20,30,50,52,35,55,65]
rpm_limit=45

def check():
    exceedLimit = [1 if x > rpm_limit else 0 for x in rpm] 
    return sum(exceedLimit)

print('RPM exceeded the limit %s times' % check())

Returns: 返回值:

RPM exceeded the limit 4 times

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM