Python Count List Items in a List

Let's say I have the following list:

L=[ [0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0] ] 

I want to write code, take such a list and say whether the number "1s" in each separate list is equal to some number x. Therefore, if I typed the code (L, 3), return will be "True", because each list from L contains 3 '1s'. But if I entered the code (L, 2), then the return would be "False". I am new to all programs, so I'm sorry that my question is hard to understand. Any help would be appreciated.

+4
source share
4 answers

To find out if each subword has 3 1,

 all( x.count(1) == 3 for x in L ) 

Or as a function:

 def count_function(lst,number,value=1): return all( x.count(value) == number for x in lst ) L=[ [0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0] ] print(count_function(L,3)) #True print(count_function(L,4)) #False print(count_function(L,1,value=0)) #True 
+7
source

If L is your base list and n is the number 1 that you expect in each "sublist", then the check looks like this:

 map(sum, l) == [n] * len(l) 

The whole function along with the tests is as follows:

 >>> def check(l, n): return map(sum, l) == [n] * len(l) >>> L=[ [0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0] ] >>> check(L, 3) True >>> check(L, 2) False 

EDIT: Alternative solutions include, for example:

but I believe that the cleanest approach is that one of the other respondents gave:

 all(i.count(1) == n for i in l) 

This is even quite self-evident.

+1
source

Assuming your lists only contain 1 and 0, you can easily count them: sum(sl) . You can get a set of unique counters for subscriptions and verify that they all have three 1s as follows:

 set( sum(sl) for sl in L ) == set([3]) 

While a bit confusing compared to using the all() approach, this method also allows you to check that all sub-lists have the same number of units without specifying a number:

 len(set( sum(sl) for sl in L )) == 1 

You can even β€œclaim” that all subcategories should have the same amount of 1 and detect this number in one operation:

 [n] = set( sum(sl) for sl in L ) 

This assigns the number 1 in each sub-list n , but raises the value of ValueError if the signatures do not have all the same numbers.

+1
source
 def all_has(count, elem, lst) """ensure each iterable in lst has exactly `count` of `elem`""" return all(sub_list.count(elem) == count for sub_list in lst) >>> L = [ [0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0] ] >>> all_has(3, 1, L) True >>> all_has(2, 0, L) False 
0
source

Source: https://habr.com/ru/post/1432832/


All Articles