city = ['michigan','toronto;,michigan','denver','michigan','toronto']
for line in lines:
code <>
print ("Found ", count_value,"matching ",city)
預期產量:密歇根州:3 托頓托:2 丹佛:1
我如何存盤 count_value 以參考或映射到城市,以便我可以列印回圈運行的串列中出現最多的前 3 個城市。我已經完成了代碼并且可以計算在串列中找到一個城市的次數,但是我如何列印串列中城市的前 3 個最高計數
uj5u.com熱心網友回復:
你要找的東西叫做字典;這在python中真的很容易。您需要創建一個包含城市的字典(它們可能首先需要默認值),然后當您執行查找邏輯時,為該城市分配值(這是一個未經測驗的示例):
dict = {'michigan','toronto;,michigan','denver','michigan','toronto'}
for line in lines:
code <>
dict[city] = count_value
uj5u.com熱心網友回復:
您可以使用 aCounter()自動累積串列中出現的總數并將其設定為索引值。
from collections import Counter
city = ['michigan', 'toronto', 'michigan', 'denver', 'michigan', 'toronto']
print(Counter(city)) # Outputs -> Counter({'michigan': 3, 'toronto': 2, 'denver': 1})
# To sort by most frequent cities first.
print(Counter(city).most_common()) # ('michigan', 3), ('toronto', 2), ('denver', 1)
要獲得您想要的確切輸出,您可以遍歷串列并將每個城市的值插入到一個字串中:
from collections import Counter
city = ['michigan', 'toronto', 'michigan', 'denver', 'michigan', 'toronto']
city = Counter(city).most_common() # Convert city into a Counter of all the city occurrences.
totalCityString = ""
for key in city: totalCityString = key[0] ": " str(key[1]) " "
print(totalCityString) # Outputs -> 'michigan: 3 toronto: 2 denver: 1'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/337596.html
上一篇:Android布局未加載
下一篇:根據嵌套值之一對地圖進行排序
