让data = [[3,7,2],[1,4,5],[9,8,7]]
假设我想对列表中每个列表的索引元素求和,例如在矩阵列中添加数字以获得单个列表。我假设数据中的所有列表的长度都是相等的。
print foo(data)
[[3,7,2],
[1,4,5],
[9,8,7]]
_______
>>>[13,19,14]
如何在不出现索引超出范围错误的情况下遍历列表列表?也许是拉姆达?谢谢!
You could try this:
In [9]: l = [[3,7,2],[1,4,5],[9,8,7]]
In [10]: [sum(i) for i in zip(*l)]
Out[10]: [13, 19, 14]
This uses a combination of zip
and *
to unpack the list and then zip the items according to their index. You then use a list comprehension to iterate through the groups of similar indices, summing them and returning in their 'original' position.
To hopefully make it a bit more clear, here is what happens when you iterate through zip(*l)
:
In [13]: for i in zip(*l):
....: print i
....:
....:
(3, 1, 9)
(7, 4, 8)
(2, 5, 7)
In the case of lists that are of unequal length, you can use itertools.izip_longest
with a fillvalue
of 0
- this basically fills missing indices with 0
, allowing you to sum all 'columns':
In [1]: import itertools
In [2]: l = [[3,7,2],[1,4],[9,8,7,10]]
In [3]: [sum(i) for i in itertools.izip_longest(*l, fillvalue=0)]
Out[3]: [13, 19, 9, 10]
In this case, here is what iterating over izip_longest
would look like:
In [4]: for i in itertools.izip_longest(*l, fillvalue=0):
...: print i
...:
(3, 1, 9)
(7, 4, 8)
(2, 0, 7)
(0, 0, 10)
对于任何矩阵(或其他雄心勃勃的数值)运算,我建议您研究 NumPy。
解决问题中显示的沿轴的数组总和的示例是:
>>> from numpy import array
>>> data = array([[3,7,2],
... [1,4,5],
... [9,8,7]])
>>> from numpy import sum
>>> sum(data, 0)
array([13, 19, 14])
这是 numpy 的 sum 函数的文档:http: //docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html#numpy.sum
特别是第二个参数很有趣,因为它可以轻松指定应该总结的内容:所有元素或仅可能是 n 维数组(如)的特定轴。
这将为您提供每个子列表的总和
data = [[3,7,2],[1,4],[9,8,7,10]]
list(map(sum, data))
[12, 5, 34]
如果你想对所有元素求和并只得到一个总和,那么使用这个
data = [[3,7,2],[1,4],[9,8,7,10]]
sum(sum(data, []))
51
>>> data = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> for column in enumerate(data[0]):
... count = sum([x[column[0]] for x in data])
... print 'Column %s: %d' % (column[0], count)
...
Column 0: 3
Column 1: 6
Column 2: 9
这确实取决于您假设所有内部列表(或行)的长度相同,但它应该做您想要的:
sum_list = []
ncols = len(data[0])
for col in range(ncols):
sum_list.append(sum(row[col] for row in data))
sum_list
Out[9]: [13, 19, 14]
def sum(L):
res = list()
for j in range(0,len(L[0])):
tmp = 0
for i in range(0,len(L)):
tmp = tmp + L[i][j]
res.append(tmp)
return res
将不同或相同长度的列表相加的最简单的解决方案是:
total = 0
for d in data:
total += sum(d)
一旦你理解了列表理解,你就可以缩短它:
sum([sum(d) for d in data])
对于数据是字符串列表的情况。逐元素求和或连接字符串列表的列表。
>>> a = [list('abc'),list('def'),list('tyu')]
>>> a
[['a', 'b', 'c'], ['d', 'e', 'f'], ['t', 'y', 'u']]
>>> [''.join(thing) for thing in zip(*a)]
['adt', 'bey', 'cfu']
>>>
numArr = [[12, 4], [1], [2, 3]] sumArr = 0 sumArr = sum(sum(row) for row in numArr) print(sumArr) the answere: 22
我做了什么:当你像这样做“for”时,例如:[row.append(1) for row in numArr] 列表将变为:[[12, 4, 1], [1, 1], [2 , 3, 1]] 我使用了 python 中的 sum() 函数,该函数获取列表并对其进行迭代,并将列表中所有数字的总和。当我执行 sum(sum()) 时,我得到了大列表中所有列表的总和。
此解决方案假定一个方阵并使用两个 for 循环来循环列和行,在此过程中逐列添加。结果以列表形式返回。
def foo(data):
# initialise length of data(n) and sum_of_col variable
n = len(data)
sum_of_col = []
# iterate over column
for col_i in range(n):
# column sum
col_count = 0;
#iterate over row
for row_i in range(n):
col_count += data[row_i][col_i]
# append sum of column to list
sum_of_col.append(col_count)
return sum_of_col