python 3键=lambda heappush

2024-05-23 17:16:11 发布

您现在位置:Python中文网/ 问答频道 /正文

这和Python2配合得很好 第二个参数类型有时会从str改为dict,但这没问题

pyton3我有这个 TypeError:“dict”和“str”的实例之间不支持“<;”

我已经看到这个TypeError: '<' not supported between instances of 'tuple' and 'str'理解并且heapq with custom compare predicate给出了一个很好的答案:

…heapq模块中的函数有点麻烦(,因为它们不是面向对象的),并且总是要求我们的堆对象(heapified list)作为第一个参数显式传递。我们可以通过创建一个非常简单的包装类来一举两得,它允许我们指定一个键函数,并将堆作为一个对象呈现。。。。在

但是创建一个新类要复杂得多。在

在8.5.2中也是https://docs.python.org/3.6/library/heapq.html。Priority Queue Implementation Notes部分,但我希望使用tuple(int,str)或tuple(int,dic)。在

我也见过How to use lambdas in python heapq?看起来不错吗?在

其他有趣的方法是How to make heapq evaluate the heap off of a specific attribute?和{a6}

有人在吗?(吉姆)

python3中的这个示例程序错误来自http://python-prepa.github.io/information_theory.html

occurrences={'A': 5, 'R': 2, 'B': 2, 'C': 1, 'D': 1}
tas = [(occ, lettre) for (lettre, occ) in occurrences.items()]
heapify(tas)
while len(tas) >= 2:
    print (tas)
    occ1, noeud1 = heappop(tas)
    occ2, noeud2 = heappop(tas)
#    print(type(noeud1))
#    print(type(noeud2))
    t=(occ1 + occ2, {0: noeud1, 1: noeud2})
#    print(occ1,noeud1)
#    print(occ2,noeud2)
#    print(t)
    heappush(tas, t)
#    heappush(tas, (occ1 + occ2, {0: noeud1, 1: noeud2}))
print (tas)

Tags: of对象函数htmldictprintheapqstr