2017-10-07 76 views
0

我想知道是否有可能使這與列表理解。 行「總= 0」是什麼讓錯誤python列表理解for循環和語句

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) 

所有我能想到的是

result = [total for lis in listoflists total=0 for i in lis if i==1 total +=1] 

不過,當然是不行的,我無法找到如何處理報表未IFS或

任何幫助,將不勝感激

+0

單靠列表理解是不可能的。 –

回答

0

這是不可能的,只是簡單的列表推導。

如果您還可以使用一些函數,則可以使用[sum(filter(lambda x: x == 1, l)) for l in listsoflists]

編輯:

[l.count(1) for l in listsoflists]當然更好。

1

您可以簡單地這樣做是爲了得到1的總數:

result = sum([l.count(1) for l in listoflists]) 

或情況下,你需要在子陣列個別情況,這應該這樣做:

result = [l.count(1) for l in listoflists] 

所以,

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) 

和:

listoflists = [[1,2,5],[1,1,1],[1,2,2,2,1]] 
result = [l.count(1) for l in listoflists] # result = [1, 3, 2] 
1
> 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] 
0

雖然在這種情況下

[l.count(1) for l in listoflists] 

是一種有效的答案。

從概念上來說,您可以使用reduce來處理您的案例total中的一些任意聚合(不同於簡單總和)。

from functools import reduce 
[reduce(lambda total,x:total + (1 if x==1 else 0),l,0) for l in listoflists]