Как мне найти сумму каждого отдельного списка в моем массиве? - PullRequest
2 голосов
/ 11 февраля 2020

Я пытаюсь найти индивидуальную сумму каждого списка в моем массиве, а затем найти список с самой большой суммой.

Я пытался использовать:

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)

Ответы [ 3 ]

3 голосов
/ 11 февраля 2020

Попробуйте использовать:

np.sum(l, axis=1)

Или вы @ furas ответите, или используйте:

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

Изменили list на l, поскольку оно переопределяет ключевое слово list .

2 голосов
/ 11 февраля 2020

Используя понимание списка, вы можете вычислить все значения

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

new = [sum(x) for x in data]

print(new)

[10, 26, 42]
1 голос
/ 11 февраля 2020

Если вам разрешено использовать numpy, то вы также можете сделать следующее:

ans = []
for lst in arr1:
    ans.append(np.sum(lst))
print(ans)

[10, 26, 42]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...