【问题标题】:Finding top dictionary values查找顶级字典值
【发布时间】:2020-09-22 08:36:25
【问题描述】:

我汇总了 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) 但它给出了错误计数器未定义。我还导入了 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)

【问题讨论】:

  • 你能给出输入和预期输出吗?

标签: python dictionary counter


【解决方案1】:

for 循环中的 return 语句导致函数在循环的第一次迭代期间终止。如果您要做的是返回 n 个最常见的项目,您可以简单地编写

def top_items(items, n=3):
   counts = collections.Counter(items)
   return counts.most_common(n)

【讨论】:

  • 谢谢@joantan!一个奇怪的问题。如果我只想返回键而不是值,我不会想到如何对列表进行切片。即您的代码给出:[(洛杉矶,15),(丹佛,10),(西雅图,5)],您将如何只返回城市,而不是计数。谢谢!
  • 您可以将其转换为字典,然后检索字典的键或使用列表理解/映射。所以dict(counts.most_common(n)).keys()[t[0] for t in counts.most_common(n)]
  • 这也可以:next(zip(*counts.most_common(n)))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多