python - 我如何找到数组中每个单独列表的总和?

标签 python arrays python-3.x list

我想做的是找到数组中每个列表的单独总和,然后找到总和最大的列表。

我尝试使用:

np.sum(list)

这样做的问题是,它将每个列表的总和相加以获得总和。例如:

[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
#np.sum() would return 78 because it calculates 10+26+42 = 78

这就是我想要得到的:

[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
#list1 = 10, list2 = 26, list3 = 42
#The list with the max value is list3 with 42

这是我的代码:

#Sorry if this code is messy, I'm still new to this and it took me a few days to get here
#Basically this code takes a gird and finds the biggest area (i.e: width and height) of the grid

def FindAnswer(height, width, x, y, startx, starty):
  global origWidth, result

  #Find the values
  value = [row[startx:width] for row in plot[starty:height]]
  result.append(value)

  if width < x:
    #Raise the index im looking at and reset value
    startx += 1
    width += 1

    FindAnswer(height, width, x, y, startx, starty)

  elif height < y:
    #Reset width while going to a new row
    width = origWidth
    startx = 0

    #Go to a new row
    starty += 1
    height += 1

    FindAnswer(height, width, x, y, startx, starty)

plot = [[1, 2, 3, 4], 
     [5, 6, 7, 8], 
     [9, 10, 11, 12]]

result = []
#size of grid
x = 4 #amount of numbers in each list
y = 3 #number of rows

#Size of area I'm looking for
width = 1 #x >= width > 0
height = 2 #y >= height > 0
origWidth = width

startx = 0
starty = 0

FindAnswer(height, width, x, y, startx, starty)

print(result)

最佳答案

尝试使用:

np.sum(l, axis=1)

或者你@furas的答案,或者使用:

print(list(map(sum, l)))

list 更改为 l,因为它会覆盖 list 关键字。

关于python - 我如何找到数组中每个单独列表的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60160802/

相关文章:

python - 车辆路径问题如何用or-tools只让部分团回车场?

python - 使用 itertools 的部分多处理 pool.map 的 2 个以上参数

Python:未定义全局名称(但它不是全局变量)

python - 为什么 venv 在 rsync 后中断?

arrays - C 中 sizeof() 运算符中 "comma"运算符的行为

python-3.x - OpenAI 耳语;找不到文件错误 : [WinError 2] The system cannot find the file specified

python - 从 Windows 主机在远程 Linux 机器上运行部分 Python 单元测试

python - 在 Numpy 数组中每行保留最大 N 个值

javascript - 对毫秒数组求和

arrays - 平均阵列Powershell的一部分