简体   繁体   English

使用 list() 显式创建的列表上出现错误“'NoneType' 类型的对象没有 len()”

[英]Error “object of type 'NoneType' has no len()” on list explicitely created with list()

I am new to Python and for my AI class I was trying to do an Huffman encoding program for strings.我是 Python 和我的 AI class 的新手,我试图为字符串做一个霍夫曼编码程序。 For that, I need to build an optimized weigthed tree.为此,我需要构建一个优化的加权树。 Thing is, I'm trying to call the len() function on a variable explicitly created with the list() built-in function, but it doesn't work.问题是,我试图在使用list()内置 function 显式创建的变量上调用len() function,但它不起作用。 What am I doing wrong?我究竟做错了什么?

Here's the code:这是代码:

def opti(text):
        occ = occurences(text)
        occ = dict(sorted(occ.items(), key=lambda item: item[1]))
        l_n = list(occ.items())
        while len(l_n) > 1:
                n1 = l_n.pop(0)
                n2 = l_n.pop(0)
                n = Noeud(n1[1] + n2[1], n1, n2)
                l_n.append((n, n.valeur))
                l_n = l_n.sort(key=lambda tup: tup[1])
        return l_n

class Noeud:
        def __init__(self, value, left, right):
                self.value = value
                self.left = left
                self.right = right

If I print the variable l_n I'm clearly getting a list so I don't understand why this isn't working.如果我打印变量l_n我显然会得到一个列表,所以我不明白为什么这不起作用。 I've already tried looking for an answer on other topics but the answer mostly were about other functions modifying the type to NoneType whereas here I'm clearly using the list constructor function.我已经尝试寻找其他主题的答案,但答案主要是关于将类型修改为NoneType的其他函数,而在这里我显然使用了列表构造函数 function。

The function occurences returns a dictionary containing the number of occurences of each character in a string, if that matters. occurences出现返回一个字典,其中包含字符串中每个字符的出现次数,如果这很重要的话。

l_n = l_n.sort(key=lambda tup: tup[1])

Here sort() function sorts list inplace.这里sort() function 对列表进行就地排序。 Hence it retuns None.因此它返回无。

Instead try this:而是试试这个:

l_n = sorted(l_n, key=lambda tup: tup[1])

OR Just this: l_n.sort(key=lambda tup: tup[1])或者就是这个: l_n.sort(key=lambda tup: tup[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM