gpt4 book ai didi

python - SortedDict 键 : TypeError: '<' not supported between instances of 'str' and 'int'

转载 作者:行者123 更新时间:2023-12-01 23:20:11 24 4
gpt4 key购买 nike

请帮助我理解为什么在以下代码中设置 SortedDictkey 参数:

from sortedcontainers import SortedDict
SortedDict({1:2, 0:1}) # works
SortedDict({1:2, 0:1}, key=lambda x: x) # TypeError
SortedDict({'a':2, 0:1}, key=lambda x: 1 if isinstance(x,str) else x) # TypeError

出现以下错误:

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

如何修复示例?非常感谢您的帮助!

最佳答案

来自文档:http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html

The key-function argument must be provided as a positional argument and must come before all other arguments.

因此您的代码应为:

from sortedcontainers import SortedDict
SortedDict({1:2, 0:1})
SortedDict(lambda x: x, {1:2, 0:1})
SortedDict(lambda x: 1 if isinstance(x,str) else x, {'a':2, 0:1})

关于python - SortedDict 键 : TypeError: '<' not supported between instances of 'str' and 'int' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68204310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com