Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python counting elements of a list within a list

Tags:

python

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 a code will take a list like this one and tell me if the number of '1s' in each individual list is equal to some number x. So if I typed in code(L,3) the return would be "True" because each list within L contains 3 '1s'. But if I entered code(L,2) the return would be "False". I'm new to all programming, so I'm sorry if my question is hard to understand. Any help would be appreciated.

like image 806
user1653420 Avatar asked Jan 16 '23 15:01

user1653420


2 Answers

To see if each sublist has 3 1's in it,

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
like image 112
mgilson Avatar answered Jan 18 '23 22:01

mgilson


Assuming your lists contain only 1's and 0's, you can count the ones quite easily: sum(sl). You can get the set of unique counts for sub-lists and test that they all have three 1's as follows:

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

While a little obscure compared to using the all() approach, this method also lets you test that all sub-lists have the same number of ones without having to specify the number:

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

You can even "assert" that the sub-lists must all have the same number of 1's and discover that number in one operation:

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

This assigns the number of 1's in each sub-list to n, but raises a ValueError if the sub-lists don't all have the same number.

like image 22
Marcelo Cantos Avatar answered Jan 19 '23 00:01

Marcelo Cantos