如果列表中的元素至少有一个1值,则向Count = 0添加+1。蟒蛇

时间:2013-02-14 22:08:59

标签: python list count add

count_element_has_1 = 0
count_all_0 = 0   

my_list = [[0,0,1],[1,1,0,1],[0,0,0,0]]

我想检查列表中的每个元素是否至少有1,然后向count_element_has_1添加+1,如果它们都是0,则将+1添加到count_all_0

所以在这种情况下,它看起来像

count_element_has_1 = 2
count_all_0 = 1

4 个答案:

答案 0 :(得分:2)

for lst in my_list:
    if 1 in lst:
       count_element_has_1 += 1
    elif lst.count(0) == len(lst):
       count_all_0 += 1

根据列表,第二个条件可能更好,例如:

elif all(x==0 for x in lst):
    count_all_0 += 1

因为这允许短路。

答案 1 :(得分:1)

您可以使用sum功能,并结合列表推导。

如果列表中的其他数字可以包含01,请尝试以下操作:

count_has_1 = sum(1 for element in my_list if 1 in element)
count_all_0 = sum(1 for element in my_list if all(e == 0 for e in element))

如果你知道肯定这些列表只包含 01,那么你也可以这样做:

count_has_1 = sum(map(any, my_list))
count_all_0 = len(my_list) - count_has_1

第一行是使用Python将10解释为TrueFalse的事实,反之亦然,首先将每个子列表映射到是否为值是真的,例如[0,1,0] -> True,然后汇总由此产生的布尔值列表,例如: [True, False, True] -> 2

答案 2 :(得分:0)

您可以使用collections.Counter()O(N^2)复杂性:

In [22]: lis=[[0,0,1],[1,1,0,1],[0,0,0,0]]

In [23]: from collections import Counter

In [24]: count_element_has_1 = 0

In [25]: count_all_0 = 0

In [26]: for x in lis:
    c=Counter(x)
    if c[0]==len(x):
        count_all_0 +=1
    elif c[1]>0:    
        count_element_has_1 +=1
   ....:         

In [27]: count_element_has_1
Out[27]: 2

In [28]: count_all_0
Out[28]: 1

答案 3 :(得分:0)

my_list = [[0,0,1],[1,1,0,1],[0,0,0,0],[4,0,88]]
#
count_has_1 = sum(1 in sub for sub in my_list)
print count_has_1 # prints 2
#
count_all_0 = sum(not any(sub) for sub in my_list)
print count_all_0 # prints 1

如果子列表中只有0和1,那么计算这两个类别是没用的:

my_list = [[0,0,1],[1,1,0,1],[0,0,0,0]]
#
count_has_non0 = sum(map(any,my_list))
print count_has_non0 # prints 2
#
print len(my_list) - count_has_1  # prints 1