亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何跟蹤此列表中的頻率?

如何跟蹤此列表中的頻率?

jeck貓 2021-12-16 15:14:25
我想弄清楚如何跟蹤用戶輸入的列表中數字的頻率。我的意思是:假設有人輸入 45 兩次,52 次輸入 52 次,22 次輸入,代碼會打印出類似“頻率:45-2、52-3 和 22-1”的內容。提出這個問題的其他代碼是針對已經在代碼中創建的列表,但這個不同,因為用戶正在添加到列表中。import sysprint ("After inputting this data, the sum, average, maximum and minimum number will be printed")temperatureList = list()weather=int(input("Enter the amount of days that you are looking at for the weather:"))print("Enter the high temperature for those next days: ")for i in range(int(weather)):   k=int(input(""))   temperatureList.append(int(k))sm=sum(temperatureList)avg=sm/weatherprint("SUM = ",sm)print("AVERAGE = ",avg)temperatureList.sort()print("This is the numbers from low to high", temperatureList)print("Maximum number in the list is:", max(temperatureList), "and the minimum number is: ", min(temperatureList))while True:   action = int(input("Input add if you want to add to the list again. Or remove if you want to remove from the list, or end if you want to end this program"))   if action == add:      print("Enter what you want to be added ")      add = int(input(""))      temperatureList.append(add)      print(temperatureList)      sm = sum(temperatureList)      avg = sm / weather      print("SUM = ", sm)      print("AVERAGE = ", avg)      temperatureList.sort()      print("This is the numbers from low to high", temperatureList)   elif action == remove:      if len(temperatureList) > 1:         del temperatureList[-1]         print(temperatureList)         sm = sum(temperatureList)         avg = sm / weather         print("SUM = ", sm)         print("AVERAGE = ", avg)  else:     print("Everything removed from the list")   elif action == end:      sys.exit()
查看完整描述

2 回答

?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

您需要所謂的直方圖。您可以使用 Python 字典創建一個;使用你得到的答案作為字典的鍵,答案算作相應的值。每當您從用戶那里得到答案時,請檢查字典是否已經有該答案的條目。如果不是,則將該值設置為 1。如果鍵存在,則獲取計數,將其加一,并存儲新計數。然后,您可以在開始另一輪循環之前打印字典(或它的某種表示)。

如果您不熟悉 Python 詞典,請先查看文檔。


查看完整回答
反對 回復 2021-12-16
?
catspeake

TA貢獻1111條經驗 獲得超0個贊

GeeksforGeeks上有一個很好的例子來說明這個問題。閱讀本文將幫助您解決問題。


這是他們為解決方案提供的 Python 代碼:


# Python program to count the frequency of  

# elements in a list using a dictionary 


def CountFrequency(my_list): 


    # Creating an empty dictionary  

    freq = {} 

    for item in my_list: 

        if (item in freq): 

            freq[item] += 1

        else: 

            freq[item] = 1


    for key, value in freq.items(): 

        print ("% d : % d"%(key, value)) 


# Driver function 

if __name__ == "__main__":  

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


    CountFrequency(my_list) 

這只是遍歷列表,將列表的每個不同元素用作字典中的鍵,并將該鍵的相應計數存儲為值。


它的時間復雜度為 O(n),其中 n 是列表的長度,因為它遍歷列表中的每個值。


查看完整回答
反對 回復 2021-12-16
  • 2 回答
  • 0 關注
  • 239 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號