如何检查列表中是否有两个以上与0不同的值?(Python)

问题描述 投票:1回答:1

我如何创建一个函数,如果列表中有2个或多个与0不同的项,则返回true,如果列表中少于2个非0的项,则返回false。

(错误的代码,您可以理解)

list=[0, 0, 0, 0, 0, 1, 0 , 4]
def checker:
    if > 2 items in list are > 0:
        return True
    else:
        return False

我实际上如何在python中做到这一点?

python list function
1个回答
2
投票
def checker(l, thresh=2):
    return len([i for i in l if i > 0]) >= thresh

0
投票
list1=[0, 0, 0, 0, 0, 1, 0 , 4]
if len([x for x in list1 if x!=0 ])>1:
     print('True')
else:
     print('False')

0
投票

尝试:

def checker(lst):
    return len([element for element in lst if element != 0]) >= 2
© www.soinside.com 2019 - 2024. All rights reserved.