count_element_has_1 = 0
count_all_0 = 0
my_list = [[0,0,1],[1,1,0,1],[0,0,0,0]]
我想检查列表中的每个元素是否至少有 1,然后将 +1 添加到 count_element_has_1,如果它们都是 0,则将 +1 添加到 count_all_0
所以在这种情况下,它看起来像
count_element_has_1 = 2
count_all_0 = 1
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
因为这允许短路。
您可以使用该sum
函数,并结合列表推导。
如果列表可以包含除and以外的其他数字,请尝试以下操作:0
1
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))
如果您确定列表仅 0
包含and 1
,您也可以这样做:
count_has_1 = sum(map(any, my_list))
count_all_0 = len(my_list) - count_has_1
1
第一行是使用 Python 将and解释0
为True
and的事实,False
反之亦然,首先将每个子列表映射到是否有任何值为真,例如[0,1,0] -> True
,然后总结得到的布尔值列表,例如[True, False, True] -> 2
。
您可以使用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
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