簡體   English   中英

Python-查找列表中最高整數的索引值

[英]Python - Finding the index value of the highest integer in a list

我目前正在編寫一個程序,向用戶介紹他/她的視頻游戲使用情況。 要求用戶輸入一周中每一天花費的游戲時間。 然后程序告訴他們

  • 一周總共花了多少小時進行游戲,
  • 每天花在游戲上的平均時間,
  • 一天中最多的時間花在游戲上。

這是我的代碼現在的樣子;

while True:
name = input("Hello! Please enter your name: ")
if name.isalpha():
    break
else:
    print("Please enter a valid name.")

print("Hello {}! Lets get started!".format(name))

week_hours = []

for i in range(7):
while True:
    try:
        hours = int(input("How many hours did you spend gaming on day 
{}".format(i+1)))
        week_hours.extend([hours])
        break

    except ValueError:
        print("please enter a valid integer.")

total = sum(week_hours)
print("you spent a total of {} Hours gaming in the past 7 days!".format(total))

average = total/7
print("On average, you spent {} hours gaming per day.".format(average))

(while循環用於數據驗證,並確保在不應該輸入的時候不能輸入字母/數字。)

我目前正在寫一份打印聲明,告訴用戶一天中花在游戲上的時間最多。 我在這里

print("You played video games the most on day {}, spending {} hours!".format())

當被問及用戶花了多少小時進行游戲時,用戶的輸入存儲在列表中。 一旦用戶在列表中輸入了7個值(一周中的每一天一個),它將跳出循環並繼續執行程序的其余部分。

現在,開始討論這個問題。

我如何能夠返回存儲在該列表中的最高int的索引值,然后使用“ .format”將其放入print語句中?

抱歉。 首先,我誤解了這個問題。 如果需要獲取列表中最大數字的索引。 您可以嘗試以下方法:

# hours is your list of values.
hours = [...]
highest_value = max(hours) 
index = hours.index(highest_value)

請注意,如果列表中重復的最大值不起作用。

如果您只需要最大值,那么max就是您所需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM