简体   繁体   English

子列表最高 sum() 的索引

[英]Index of the highest sum() of sublists

Given a finite list of n sub-lists:给定n个子列表的有限列表:

my_list = [[2, 9999], [318, 9999], [990, 9999], [9, 9999], [7767, 9999]]

I want a one-liner concise procedure that returns the index of the sub-list with the highest sum().我想要一个单行简洁的过程,它返回具有最高 sum() 的子列表的索引。

If in the event 2 or more sub-lists have an equal sum(), then return the first.如果事件中 2 个或更多子列表具有相等的 sum(),则返回第一个。

My code:我的代码:

for ksu in key_set_unique:
   print(sum(ksu))

You can use max with sum as key您可以使用maxsum作为键

index = my_list.index(max(my_list, key=sum))
my_list = [[2, 9999], [318, 9999], [990, 9999], [9, 9999], [7767, 9999]]

temp = []

for sub_list in my_list:
    x = sum(sub_list)
    temp.append(x)

ind_value = max(temp)

print(temp.index(ind_value))

I ran a for loop to get the sum of inherited list stored in variable my_list.我运行了一个 for 循环来获取存储在变量 my_list 中的继承列表的总和。 And that sum is stored in the new list called temp.该总和存储在名为 temp 的新列表中。

Now simply i got index of maximum value stored in temp as index position will remain same so i can get the inherited list with maximum sum value.现在我得到了存储在 temp 中的最大值索引,因为索引 position 将保持不变,因此我可以获得具有最大总和值的继承列表。 ( my_list[0] = temp[0] ) ( my_list[0] = temp[0] )

Since you explicitly asked for a one-liner, here it is:由于您明确要求单线,这里是:

>>> list(map(sum, my_list)).index(max(map(sum, my_list)))
4

This line creates a list of sums using the map function and finds a value in said list using index .此行使用map function 创建总和列表,并使用index在所述列表中找到一个值。 The value that is searched for is the max value of the list of sums mentioned earlier.搜索的值是前面提到的总和列表的最大值。

Note that this computes the sums of my_list 's elements twice, which isn't necessary.请注意,这会计算my_list元素的总和两次,这不是必需的。 Solution without the one-line requirement:无单行要求的解决方案:

>>> sum_list = list(map(sum, my_list))
>>> sum_list.index(max(sum_list))
4

# index with element # 索引元素

element, index = max([(sum(item), i) for i, item in enumerate(my_list)])
print(element, index)

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

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