我在总结两个方面需要帮助。
让我说[[0,1,2],[3,4,5]]作为我的维度,将这些数字相加将返回第15行。
def sum_dimensions(x):
x = []
answer = sum(x)
return int(x)
赞赏我在代码中指出我的错误。
答案 0 :(得分: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 :(得分: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)
会抛出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)
答案 2 :(得分:0)
这是Python,而不是C.
ar = [[0,1,2],[3,4,5]]
result = sum ( [sum(block) for block in ar] )
答案 3 :(得分:0)
如果您正在进行其他线性代数,则可能值得考虑numpy
:
import numpy as np
x = np.array( [[0,1,2],[3,4,5]] )
print np.sum(x)
答案 4 :(得分:0)
试试这个,
>>>sum([sum(i) for i in [[0,1,2],[3,4,5]]])
输出:
15
答案 5 :(得分:0)
你可以试试这个:
>>> l = [[0,1,2],[3,4,5]]
>>>
>>> sum(a for v in l for a in v)
15
答案 6 :(得分:0)