【问题标题】:Sorting tuples in python based on their values [duplicate]根据值对python中的元组进行排序[重复]
【发布时间】:2014-07-18 02:29:13
【问题描述】:

我正在尝试使用以下代码打印前 10 个常用词。但是,它不起作用。关于如何修复它的任何想法?

def reducer_count_words(self, word, counts):
    # send all (num_occurrences, word) pairs to the same reducer.
    # num_occurrences is so we can easily use Python's max() function.
    yield None, (sum(counts), word)




# discard the key; it is just None
def reducer_find_max_10_words(self, _, word_count_pairs):
    # each item of word_count_pairs is (count, word),
    # so yielding one results in key=counts, value=word

        tmp = sorted(word_count_pairs)[0:10]
        yield tmp

【问题讨论】:

  • @Veedrac:更类似于这个问题:stackoverflow.com/questions/3121979/…
  • @Leftium 我强烈不同意你对这个问题的解释。此外,到底是如何“它不起作用。关于如何解决它的任何想法?”获得支持?
  • @Veedrac:我的解释是基于问题标题和提问者对其他答案的回答。
  • @Leftium 我坚持我的观点,但我并不真正关心这种质量问题。

标签: python sorting tuples


【解决方案1】:

使用collections.Counter 及其most_common 方法:

>>>from collections import Counter
>>>my_words = 'a a foo bar foo'
>>>Counter(my_words.split()).most_common()
[('foo', 2), ('a', 2), ('b', 1)]

【讨论】:

  • 我在我的代码中使用了这个命令,但是看到了这个错误:unhashable type 'list'。如果我想使用这种格式,似乎我不能使用most.common()
  • 嗯。那个确切的代码在我的机器上工作。
【解决方案2】:

使用collections.most_common()

例子:

most_common([n])
Return a list of the n most common elements and their counts from the most common to the least. If n is not specified, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:

>>> from collections import Counter
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

【讨论】:

  • 我在我的代码中使用了这个命令,但是看到了这个错误:unhashable type 'list'。如果我想使用这种格式,似乎我不能使用most.common()
  • 在单词列表上运行 most_common(),而不是在 (word, count) 元组上运行
【解决方案3】:
tmp = sorted(word_count_pairs, key=lambda pair: pair[0], reverse=True)[0:10]

说明:

  • sorted()key 参数允许您在比较之前对每个元素运行一个函数。
  • lambda pair: pair[0] 是一个从 word_count_pairs 中提取数字的函数。
  • reverse 按降序排序,而不是升序。

来源:


aside:如果你有很多不同的词,那么对整个列表进行排序以找到前十名是低效的。有更有效的算法。另一个答案中提到的most_common() 方法可能使用了更有效的算法。

【讨论】:

  • 非常感谢。这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-28
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 2014-12-07
  • 1970-01-01
相关资源
最近更新 更多