简体   繁体   中英

Python counting elements of a list within a list

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.

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

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

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

The whole function, along with tests, looks like this:

>>> 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 the cleanest approach is the one given by one of the other answerers:

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

It is even pretty self-explanatory.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM