Python 类型错误:“元组”和“str”的实例之间不支持“<”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41913043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:50:53  来源:igfitidea点击:

TypeError: '<' not supported between instances of 'tuple' and 'str'

pythonpython-3.xsorting

提问by rhazkoomar

I have a method that build huffman tree which is as follows:

我有一个构建霍夫曼树的方法,如下所示:

def buildTree(tuples) :
    while len(tuples) > 1 :
        leastTwo = tuple(tuples[0:2])                  # get the 2 to combine
        theRest  = tuples[2:]                          # all the others
        combFreq = leastTwo[0][0] + leastTwo[1][0]     #enter code here the branch points freq
        tuples   = theRest + [(combFreq,leastTwo)]     # add branch point to the end
        tuples.sort()                                  # sort it into place
    return tuples[0]            # Return the single tree inside the list

but while I feed the function with following parameter:

但是当我使用以下参数提供函数时:

[(1, 'b'), (1, 'd'), (1, 'g'), (2, 'c'), (2, 'f'), (3, 'a'), (5, 'e')]

I get the error as

我得到的错误是

  File "<stdin>", line 7, in buildTree
    tuples.sort()
TypeError: '<' not supported between instances of 'tuple' and 'str'

While debugging I found the error was in tuples.sort().

在调试时,我发现错误在tuples.sort().

回答by Martijn Pieters

The error is thrown because you are creating inner nodes in (priority, (node, node))form. For equal priorities, Python then tries to compare a symbol from a leaf node (so the second element in a (priority, symbol)node tuple) with the (node, node)tuple from an inner node:

抛出错误是因为您正在以(priority, (node, node))表单创建内部节点。对于相同的优先级,Python 然后尝试将来自叶节点(因此是(priority, symbol)节点元组中的第二个元素)的符号与(node, node)来自内部节点的元组进行比较:

>>> inner = (combFreq, leastTwo)
>>> inner
(2, ((1, 'b'), (1, 'd')))
>>> theRest[1]
(2, 'c')
>>> theRest[1] < inner
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'tuple'

For building a huffman tree, if you want to sort your array of nodes, you only really need to sort on the priority, ignoring the rest of the tuples (symbols or child nodes):

为了构建霍夫曼树,如果你想对节点数组进行排序,你只需要按优先级排序,忽略其余的元组(符号或子节点):

tuples.sort(key=lambda t: t[0])

With that correction, your buildTree()function produces a tree:

通过该更正,您的buildTree()函数会生成一棵树:

>>> buildTree([(1, 'b'), (1, 'd'), (1, 'g'), (2, 'c'), (2, 'f'), (3, 'a'), (5, 'e')])
(15, ((6, ((3, 'a'), (3, ((1, 'g'), (2, 'c'))))), (9, ((4, ((2, 'f'), (2, ((1, 'b'), (1, 'd'))))), (5, 'e')))))

Personally, I'd use a priority queue instead, avoiding sorting each time. See How to implement Priority Queues in Python?

就个人而言,我会改用优先队列,避免每次都进行排序。请参阅如何在 Python 中实现优先级队列?