Reputation: 3
I would like to know if is possible to make this with a list comprehension. The line "total = 0" is what gives the error
listoflists=[[1,2,5],[1,1,1],[1,2,2,2,1]]
result=[]
for lis in listoflists:
total = 0
for i in lis:
if i==1:
total+=1
result.append(total)
All i can think of is
result = [total for lis in listoflists total=0 for i in lis if i==1 total +=1]
But of course doesn't work, I can't find how to handle statements that aren't ifs or for loops (in this case the "total") in list comprehensions
any help would be appreciated
Upvotes: 0
Views: 83
Reputation: 2327
Although in this case
[l.count(1) for l in listoflists]
is an efficient answer.
Conceptually to handle some arbitrary aggregation (say different from a simple sum) in your case total
on a sublist you can use reduce.
from functools import reduce
[reduce(lambda total,x:total + (1 if x==1 else 0),l,0) for l in listoflists]
Upvotes: 0
Reputation: 5543
You can simply do this to get the total count of 1
:
result = sum([l.count(1) for l in listoflists])
or in case you need individual counts in the subarrays , this should do:
result = [l.count(1) for l in listoflists]
So,
listoflists = [[1,2,5],[1,1,1],[1,2,2,2,1]]
result = sum([l.count(1) for l in listoflists]) # result = 6(1+3+2)
and :
listoflists = [[1,2,5],[1,1,1],[1,2,2,2,1]]
result = [l.count(1) for l in listoflists] # result = [1, 3, 2]
Upvotes: 1
Reputation: 363
> listoflists=[[1,2,5],[1,1,1],[1,2,2,2,1]]
> [sum([x for x in xs if x == 1]) for xs in listoflists]
> [1, 3, 2]
Upvotes: 1
Reputation: 92854
To count the number of 1
occurrences in each sublist:
listoflists = [[1,2,5],[1,1,1],[1,2,2,2,1]]
result = [i.count(1) for i in listoflists]
print(result)
The output:
[1, 3, 2]
https://docs.python.org/3/library/stdtypes.html?highlight=count#bytes.count
Upvotes: 1
Reputation: 14519
It's not possible with just plain list comprehensions.
You can use [sum(filter(lambda x: x == 1, l)) for l in listsoflists]
if you're ok with using a few functions as well.
EDIT:
[l.count(1) for l in listsoflists]
is of course better.
Upvotes: 0