gpt4 book ai didi

python - 如何在 Python sortedcontainers 中按键正确使用 SortedSets

转载 作者:太空宇宙 更新时间:2023-11-04 02:26:39 24 4
gpt4 key购买 nike

SortedListWithKey 可以使用 lambda 函数对列表进行排序:

from sortedcontainers import SortedListWithKey

SortedListWithKey([[4, 'last'], [1, 'first']], key=lambda x: x[0])
# Result: SortedListWithKey([[1, 'first'], [4, 'last']], key=<function <lambda> at 0x107f5d730>)

但假设我需要使用 set() 来获得唯一值,documentation说它也接受一个 key= 参数来按自定义函数排序,但我无法让它工作:

from sortedcontainers import SortedSet

SortedSet([[4, 'last'], [1, 'first']], key=lambda x: x[0])

会抛出以下异常:

values = set(chain(*iterables))
TypeError: unhashable type: 'list'

有什么办法可以实现吗?

最佳答案

有序集要求元素是可散列的。您的元素是不支持散列的列表。将元素更改为元组,它将起作用:

>>> from sortedcontainers import SortedSet
>>> ss = SortedSet([(4, 'last'), (1, 'first')], key=lambda value: value[0])
>>> ss
SortedSet([(1, 'first'), (4, 'last')], key=<function <lambda> at 0x10fff4848>)

这个有序集合将按对中的第一个索引对元素进行排序。元组的好处是它们是可散列的,缺点是它们是不可变的。

考虑使用 sortedcontainers.SortedDict相反:

>>> sd = SortedDict({4: 'last', 1: 'first'})
>>> sd
SortedDict({1: 'first', 4: 'last'})
>>> sd[2] = 'second'
>>> sd.pop(4)
'last'

sorted dict 将使键保持排序顺序,并让您将值更新为您喜欢的任何内容。

关于python - 如何在 Python sortedcontainers 中按键正确使用 SortedSets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50213196/

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