簡體   English   中英

在不使用 max 或 count 函數的情況下查找最大值並計算它在列表中出現的次數

[英]Finding the max value and count how many times it appears in a list without using max or count function

我目前正在學習 python,我正在努力尋找作業的答案。 我需要根據用戶輸入創建一個列表,然后找到輸入的最高溫度並計算該溫度從輸入中出現的次數。 最后我應該輸出最高溫度以及它出現的次數。

input_temps = []
for i in range(int(input("Enter the tmeperature here: "))):
    input_temps.append(int(input()))

print(input_temps)

這是我到目前為止。

編輯:我不允許使用任何 max 或 count 函數

(注意:這是在他們更改問題以排除這些功能之前,但最后沒有解決方案)

您可以使用maxcount函數。 並更好地改進輸入消息:

input_temps = []
for i in range(int(input("Enter the number of temperatures: "))):
    input_temps.append(int(input("Enter a temperature: ")))
print(input_temps)
max_temp = max(input_temps)
print(f'{max_temp=}')
max_temp_count = input_temps.count(max_temp)
print(f'{max_temp_count=}')

演示:

Enter the number of temperatures: 3
Enter a temperature: 5
Enter a temperature: 4
Enter a temperature: 5
[5, 4, 5]
max_temp=5
max_temp_count=2

由於您現在要求一個不使用max的版本:

input_temps = []
max_temp = None
max_temp_count = None
for i in range(int(input("Enter the number of temperatures: "))):
    temp = int(input("Enter a temperature: "))
    input_temps.append(temp)
    if max_temp is None or temp > max_temp:
        max_temp = temp
        max_temp_count = 1
    elif temp == max_temp:
        max_temp_count += 1
print(f'{max_temp=}')
print(f'{max_temp_count=}')

另一種可能性是輸入所有溫度,以空格或逗號分隔:

temps = input('Enter the temperatures here: ')

temps_list = [float(s) for s in temps.split(',')]

hg = max(temps_list)
cnt = temps.count(hg)
print(f'List of temperatures: {temps}\
      \nThe highest temperature is {hg}, which appears {cnt} times.')

工作示例:

Enter the temperatures here: 3,1.1,2,3.2,6,2.2,6,5.7,5
List of temperatures: [3.0, 1.1, 2.0, 3.2, 6.0, 2.2, 6.0, 5.7, 5.0]      
The highest temperature is 6.0, which appears 2 times.

要在列表中找到最高溫度,只需使用max(input_temps) 之后,您可以設置一個從 0 開始的計數器變量,並使用 for 循環遍歷列表中的每個元素並將其與最高溫度進行比較。 如果它們相等,只需在計數器上加 1。

暫無
暫無

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

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