【问题标题】:Iterating over key/value pairs in a dict sorted by keys在按键排序的字典中迭代键/值对
【发布时间】:2010-12-29 00:32:21
【问题描述】:

我有以下代码,它只是打印字典中的键/值对(这些对按键排序):

for word, count in sorted(count_words(filename).items()):
    print word, count

但是,调用 iteritems() 而不是 items() 会产生相同的输出

for word, count in sorted(count_words(filename).iteritems()):
    print word, count

现在,在这种情况下我应该选择哪一个?我咨询了Python tutorial,但它并没有真正回答我的问题。

【问题讨论】:

    标签: python


    【解决方案1】:

    在 Python 2.x 中,两者都会给出相同的结果。它们之间的区别在于items 构造了一个包含字典全部内容的列表,而iteritems 为您提供了一个迭代器,它一次获取一个项目。一般来说iteritems 是更好的选择,因为它不需要太多内存。但是在这里您正在对结果进行排序,因此在这种情况下它可能不会产生任何显着差异。如果您有疑问,iteritems 是一个安全的选择。如果性能真的很重要,那么测量两者并查看哪个更快。

    在 Python 3.x 中,iteritems 已被移除,items 现在做了 iteritems 曾经做的事情,解决了程序员浪费时间担心哪个更好的问题。 :)

    附带说明:如果您要计算单词的出现次数,您可能需要考虑使用 collections.Counter 而不是普通的 dict(需要 Python 2.7 或更高版本)。

    【讨论】:

    • +1 哇!我不知道有这样的东西存在。非常方便!
    【解决方案2】:

    根据 Marks 的回答:在 Python 2 中,使用 iteritems(),在 Python 3 中使用 items()

    另外;如果您需要同时支持两者(并且不要使用2to3),请使用:

    counts = count_words(filename)
    for word in sorted(counts):
         count = counts[word]
    

    【讨论】:

      猜你喜欢
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 2016-01-04
      • 1970-01-01
      • 2012-03-19
      • 2017-05-30
      • 2011-07-08
      相关资源
      最近更新 更多