Skip to main content
 首页 » 编程设计

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

2024年09月07日10mayingbao

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 将使键保持排序顺序,并让您将值更新为您喜欢的任何内容。