简体   繁体   中英

python list comprehension with for loops and statements

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

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

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]
> 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]

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.

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]

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