2014-04-04 57 views

回答

0

這是你在找什麼:

data = [[0,1,2],[3,4,5]] 
sum([sum([item for item in ele]) for ele in data]) 
15 

正如@filmor指出,這可以簡化爲:

data = [[0,1,2],[3,4,5]] 
sum([sum(ele) for ele in data]) 
15 

至於爲您的代碼而言,如果你是經過[[0,1,2],[3,4,5]]作爲x的功能:

answer = sum(x) 

會THR ow一個TypeError。以下

return int(x) 

也沒有意義。使你的代碼的工作方式是:

def sum_dimensions(x): 
    answer = sum(x) 
    return answer 

data = [[0,1,2],[3,4,5]] 
total_sum = 0 
for sub_list in data: 
    total_sum += sum_dimensions(sub_list) 
+0

'總和([項目的項目中ELE ])'可以寫成'sum(ele)'。 – filmor

+1

或'sum(j for i in data for j in i)' – M4rtini

+0

這甚至更好,是的:) – filmor

0

它的Python,而不是C.

ar = [[0,1,2],[3,4,5]] 
result = sum ([sum(block) for block in ar]) 
0

如果你正在做其他線性代數,它可能是值得考慮numpy

import numpy as np 

x = np.array([[0,1,2],[3,4,5]]) 
print np.sum(x) 
+0

我不喜歡使用Numpy。忘了提及! – user2581724

0

試試這個,

>>>sum([sum(i) for i in [[0,1,2],[3,4,5]]]) 

輸出:

15 
+0

非常感謝您的回覆。 – user2581724

+0

@ user2581724如果您同意此答案,則請將其標記爲「已接受」 – fledgling

5

讓我們來看看這個。我用下面的數據我的機器上設置:

data = list(list(range(100000)) for i in range(1000)) 

我有以下結果:

In [13]: %%timeit            
sum(sum(ele) for ele in data) 
    ....: 
1 loops, best of 3: 1.15 s per loop 

In [14]: %%timeit            
sum([sum([item for item in ele]) for ele in data]) 
    ....: 
1 loops, best of 3: 3.78 s per loop 


In [15]: %%timeit            
sum(j for i in data for j in i) 
    ....: 
1 loops, best of 3: 4.92 s per loop 

In [16]: %%timeit            
sum(itertools.chain.from_iterable(data)) 
    ....: 
1 loops, best of 3: 1.61 s per loop 

In [18]: %%timeit 
sum(map(sum, data)) 
    ....: 
1 loops, best of 3: 1.16 s per loop 

不過,對於小數據集itertools變種比sum(sum變快2倍。 sum(map(sum似乎準確地映射到sum(sum(ele) for ele in data)構建

+1

現在是否有關過早優化? – Hyperboreus

+0

嘿,我雖然發電機表達式的總和會比那更有效率。很高興知道! – M4rtini

+0

@Hyperboreus號但是,這項任務是相當簡單的,並允許相同代碼複雜性的多個解決方案。因此,值得研究他們如何比較,不是嗎?例如,有趣的是,我看到'j'中的數據對於構造j中的數據有多糟糕,我沒有料到這一點。 – filmor

0

你可以試試這個:

>>> l = [[0,1,2],[3,4,5]] 
>>> 
>>> sum(a for v in l for a in v) 
15 
0

它可以通過map()sum()也可以做:

a = [[0,1,2],[3,4,5]] 
sum(map(sum, a)) #15 
相關問題