简体   繁体   English

返回一个列表,该列表具有最高的数字总和和值之和的索引

[英]Return a list with index of highest sum of numbers and the sum of the values python

I've been working on a function that takes a two dimensional list of nums as a parameter and returns a list with the index of the row with the highest sum of values and the sum of those values. 我一直在研究一个函数,该函数将nums的二维列表作为参数,并返回一个列表,其中包含具有最高值和这些值之和的行的索引。 This is as far as i've gotten. 据我所知。 I've tried accumulator, if [i]+1>i: but keep getting error message can only concanetate list not int. 我已经尝试过累加器,如果[i] +1> i:但不断收到错误消息只能使列表无效,而不能使int无效。 I've tried adding for j in newList: and too many nums print out.Can someone help me out. 我尝试在newList中添加j:并且打印了太多数字,有人可以帮帮我。 1st year programmer and really stuck. 1年级程序员,真的很固执。 When I use max error not iterable. 当我使用最大错误是不可迭代的。

def FindLargestRow(lsts):
    newList=[]
    for i in lsts:
    newList.append(sum(i))
    return newList

print(FindLargestRow([[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]))
print()

desired result is: 理想的结果是:

Start FindLargestRow [1,15] 启动FindLargestRow [1,15]

You can use the max and index functions: 您可以使用max和index函数:

 maxList = max(newList)
 return newList.index(maxList), maxList

You can map sum() to the list and find the max sum. 您可以将sum()映射到列表中并找到最大和。 With that index, you can find the index of the list that has the maximum sum. 使用该索引,您可以找到具有最大总和的列表的索引。

def FindLargestRow(lsts):
    s=map(sum,lsts)
    return s.index(max(s)),max(s)

That is, 那是,

>>> d=[[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]
>>> map(sum,d)
[6, 15, 3, 10]
>>> s=map(sum,d)
>>> s
[6, 15, 3, 10]
>>> max(s)
15
>>> s.index(max(s))
1
>>> d[s.index(max(s))]
[1, 2, 3, 4, 5]

Try the following, which uses a 2D array to keep a track of the highest sum: 尝试以下操作,该操作使用2D数组来跟踪最高总和:

def FindLargestRow(lsts):
    lengths = []
    for i in lsts:
        lengths.append([i, sum(i)])
    return max(lengths, key=lambda x:x[1])[0] 

>>> print(FindLargestRow([[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]))
[1, 2, 3, 4, 5]

You can try this: 您可以尝试以下方法:

the_list = [[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]

new_list = map(sum, the_list)


return [[i for i in range(len(the_list)) if sum(the_list[i]) == max(new_list)][0], max(new_list)]
def FindLargestRow(lsts):   
    largestSize=0
    largestRow=0


    for i in range(0,len(lsts)):


       if sum(lsts[i])>=largestSize:



           largestRow = i

           largestSize = sum(lsts[i])

return [largestRow,largestSize]

print(FindLargestRow([[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]])) print() print(FindLargestRow([[[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]))print()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM