[英]Find the sum and position of the maximum value in a list
我想創建一個函數,該函數將在數字列表中打印總和和最大值的位置,但是我不確定該怎么做。.這就是我到目前為止的開始:
我使用了類似問題的一些代碼。
def maxvalpos(variables):
max = 0
for i in range(len(variables)):
if variables[i] > max:
max = variables[i]
maxIndex = i
return (max, maxIndex)
print maxvalpos(4, 2, 5, 10)
當我運行此代碼時,它僅返回該函數只能接受1個參數。 謝謝。
然后給它一個參數,或修改定義。
print maxvalpos([4, 2, 5, 10])
要么
def maxvalpos(*variables):
執行此操作的pythonic方法:
my_list_sum=sum(my_list)
index_max=my_list.index(max(my_list))
這將找到列表的總和以及列表最大值的索引
但是代碼中的問題是:您正在向該函數發送四個變量,並且只接收一個變量。 為此,請使用:
maxvalpos([4,2,7,10])
這僅發送一個參數,即函數的列表
一種更簡單的方法
>>> from operator import itemgetter
>>> maxpos, maxval = max(enumerate(my_list), key=itemgetter(1))
例如。
>>> max(enumerate([4, 2, 5, 10]), key=itemgetter(1))
(3, 10)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.