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个最高计数
您可以使用一个Counter()
,它会自动累积列表中出现的总数,并将其设置为索引值。
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'
你要找的东西叫做字典;这在python中很简单。您需要创建一个包含城市的字典(一开始可能需要默认值),然后在执行查找逻辑时,为该城市分配值(这里是一个未经测试的示例):
dict = {'michigan','toronto;,michigan','denver','michigan','toronto'}
for line in lines:
code <>
dict[city] = count_value