[英]Sum of all numbers in the first or second place in an array
I have a 2d list, for example: 我有一个二维列表,例如:
list1 = [[1,2],[3,4],[5,6],[7,8]]
and I want to find the sum of all the numbers at the n'th place of every element. 我想在每个元素的第n位找到所有数字的总和。
For example if I want the answer for 0, I would calculate: 例如,如果我想要答案为0,则可以计算:
my_sum = list1[0][0] + list1[1][0] + list1[2][0]
or 要么
my_sum = 0
place = 0
for i in range(len(list1)):
my_sum += list1[i][place]
return my_sum
Output: 16 输出:16
Is there a more elegant way to do this? 有没有更优雅的方法可以做到这一点? Or one that uses only one line of code? 还是只使用一行代码的代码?
I mean as fictional code for example: 我的意思是虚构的代码,例如:
fictional_function(list1,place) = 16
As a generalization if you want multiple indices (eg 0 and 1) you could use reduce combined with and element-wise sum something like this: 一般而言,如果您想要多个索引(例如0和1),则可以使用reduce组合和逐元素求和,如下所示:
from functools import reduce
def fictional_function(lst, *places):
s_places = set(places)
def s(xs, ys):
return [x + y for x, y in zip(xs, ys)]
return [x for i, x in enumerate(reduce(s, lst)) if i in s_places]
list1 = [[1, 2], [3, 4], [5, 6], [7, 8]]
print(fictional_function(list1, 0))
print(fictional_function(list1, 0, 1))
print(fictional_function(list1, *[1, 0]))
Output 输出量
[16]
[16, 20]
[16, 20]
The idea is that the function s
sums two list element-wise, for example: 这个想法是,函数s
将两个列表按元素求和,例如:
s([1, 2], [3, 4]) # [4, 6]
and with reduce apply s
to a list of lists, finally filter the result for the intended indices (places) only. 并通过reduce Apply将s
应用于列表列表,最后仅对预期的索引(位置)过滤结果。
Since you are looking for a functional solution, consider operator.itemgetter
: 由于您正在寻找功能解决方案,因此请考虑operator.itemgetter
:
from operator import itemgetter
L = [[1,2],[3,4],[5,6],[7,8]]
res = sum(map(itemgetter(0), L)) # 16
For performance and simpler syntax, you can use a 3rd party library such as NumPy: 为了提高性能和简化语法,可以使用第三方库,例如NumPy:
import numpy as np
A = np.array([[1,2],[3,4],[5,6],[7,8]])
res = A[:, 0].sum() # 16
list1 = [[1,2],[3,4],[5,6],[7,8]]
ind = 0
sum_ind = sum(list(zip(*list1))[ind])
The above can be even written as function taking list and the index as input and returns the sum of the common index. 上面的代码甚至可以写成以列表和索引为输入的函数,并返回公共索引的和。 What we do in the above is first we get all the same indexes to individual lists using zip
and then chooses which index one has to be summed and passes the same to sum
function. 上面我们要做的是,首先使用zip
将所有相同的索引获取到单个列表,然后选择必须对哪个索引求和并将相同的索引传递给sum
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.