Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python sortedcontainers中按键正确使用SortedSet_Python_List_Sorting_Ordereddictionary_Sortedcontainers - Fatal编程技术网

如何在Python sortedcontainers中按键正确使用SortedSet

如何在Python sortedcontainers中按键正确使用SortedSet,python,list,sorting,ordereddictionary,sortedcontainers,Python,List,Sorting,Ordereddictionary,Sortedcontainers,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 0x107

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>)
将引发以下异常:

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>)

排序后的dict将按排序顺序保存键,并允许您将值更新为您喜欢的任何值。

hi Grant,我发现SortedSet([(1,'last'),(1,'first')],key=lambda value:value[0])返回一个包含两个元素的集,即使存在键冲突。似乎SortedSet.add()函数也不会检查与提供的键函数的键冲突。这是预期的特性还是可以改进的?这将阻止我对带有键字段的自定义类对象使用SortedSet。也许我可以把钥匙移出课堂,用它作为SortedDict的钥匙,但这听起来像是一个解决办法。我想和你核实一下。钥匙只用于排序顺序。该集合适用于所有元素。听起来你想要一个排序字典。我希望任何一个集合,包括
SortedSet
,都能基于一个键强制执行唯一性。刚刚发现我应该在我的自定义类中实现
\uuuuueq\uuuuu
\uuuuuuu散列
,以生成内置的
,从而
排序集
,以实现唯一性。关键参数基于sorted()。set()类型没有这样的参数。
>>> 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>)
>>> sd = SortedDict({4: 'last', 1: 'first'})
>>> sd
SortedDict({1: 'first', 4: 'last'})
>>> sd[2] = 'second'
>>> sd.pop(4)
'last'