如何在对象表示的对象列表中找到最小和最大的频率或单词 python

How to find the smallest and largest freq or word in an list of objects represented by an object python

我有一个表示对象列表的对象。其中每一个都代表一个词及其在文件中出现的频率。 列表中的每个对象都有一个词,以及它在文件中出现的频率。目前我收到一条错误消息 "object is not iterable".

#each object in the list looks like this
#word = "hello", 4

def max(self):
    max_list = [None, 0]
    for item in WordList:
        if item.get_freq() > max_list[1]:
            max_list[0] = item.get_word()
            max_list[1] = item.get_freq()
    return max_list

如何找到这些对象的最大和最小频率

注意:这是在 class WordList 中,get_word 和 get_freq 在创建列表中对象的 class 中。

你的问题我不是很清楚。在标题中使用 'object' 至少一次太多了。该函数不使用 self。如果 WordList 是 class,则无法对其进行迭代。等等。不过,我会尽量给你一个我认为你问的问题的答案,你可能会适应。

def minmax(items)
    """Return min and max frequency words in iterable items.

    Items represent a word and frequency accessed as indicated.
    """
    it = iter(items)
    # Initialize result variables
    try:  
        item = next(items)
        min_item = max_item = item.get_word(), item.get_freq()
    except StopIteration:
        raise ValueError('cannon minmax empty iterable')
    # Update result variables
    for item in it:
        word = item.get_word()
        freq = item.get_freq()
        if freq < min_item[1]:
            min_item = word, freq
        elif freq > max_item[1]:
            max_item = word, freq
    return min_item, max_item