查找顶级字典值
Finding top dictionary values
我汇总了 3 个词典(城市、子国家/地区、国家/地区)
我需要一个函数,它可以给出那些词典中的前 n 个结果。
到目前为止,我的代码只给出每个参数的顶部,而不是在我的参数中定义的前 3 或前 n。
def top_items(item_counts, n=3):
d = collections.Counter(item_counts)
d.most_common()
for k, v in d.most_common(n):
return (k, v)
我只尝试了 d = Counter(item_counts) 但它给出了错误 Counter is undefined。我还导入了 re 和 collections。
我正在尝试 运行
print('top cities:', top_items(cities))
print('top states:', top_items(subcountries))
print('top countries:', top_items(countries))
但得到
top cities: ('', 665)
top states: ('', 552)
top countries: ('', 502)
for 循环中的 return 语句导致您的函数在循环的第一次迭代期间终止。如果你想做的是 return n 个最常见的项目你可以简单地写
def top_items(items, n=3):
counts = collections.Counter(items)
return counts.most_common(n)
我汇总了 3 个词典(城市、子国家/地区、国家/地区)
我需要一个函数,它可以给出那些词典中的前 n 个结果。
到目前为止,我的代码只给出每个参数的顶部,而不是在我的参数中定义的前 3 或前 n。
def top_items(item_counts, n=3):
d = collections.Counter(item_counts)
d.most_common()
for k, v in d.most_common(n):
return (k, v)
我只尝试了 d = Counter(item_counts) 但它给出了错误 Counter is undefined。我还导入了 re 和 collections。
我正在尝试 运行
print('top cities:', top_items(cities))
print('top states:', top_items(subcountries))
print('top countries:', top_items(countries))
但得到
top cities: ('', 665)
top states: ('', 552)
top countries: ('', 502)
for 循环中的 return 语句导致您的函数在循环的第一次迭代期间终止。如果你想做的是 return n 个最常见的项目你可以简单地写
def top_items(items, n=3):
counts = collections.Counter(items)
return counts.most_common(n)