是否保证python排序键只能被调用一次? [英] Are python sort keys guaranteed to be called only once?
问题描述
回答另一个问题时,我最终创建了一个sortkey函数,该函数修改了字典以保存状态,然后用于排序中的后续项目.
While answering another question, I ended up creating a sortkey function which modified a dictionary in order to save state which would then be used for subsequent items in the sort.
虽然我的答案似乎起作用了,但我的问题是:python文档中是否实际上定义了sort-key每个对象仅被调用一次?这是Cpython的实现细节吗?还是排序键实际上被调用了不止一次,而我只是出于运气才得到了正确答案?
While my answer seemed to work, my question is this: Is it actually defined in the python documentation that the sort-key would only be called once per object? Is this is an implementation detail of Cpython? Or is the sort-key actually called more than once and I got the correct answer only out of luck?
sorted
的文档指出:
The documentation of sorted
states:
key指定一个参数的功能,该参数用于从每个列表元素中提取比较键:key = str.lower.默认值为无(直接比较元素)
key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly)
我不认为暗示key
每个元素只会被调用一次,但是可以在其他地方声明.
Which I don't think implies that key
will only be called once per element ... but it could be stated elsewhere.
很明显,我问这是因为它会对任何具有副作用的排序键产生影响.
Obviously I ask as this has consequences on any sort-keys which have a side effect.
推荐答案
在文档的链接部分中:
通常,键和反向转换过程比指定等效的cmp函数要快得多.这是因为对于每个列表元素,cmp被多次调用,而键和反向触摸每个元素仅一次.
这似乎是是" ...
That would seem to be a "yes" ...
这篇关于是否保证python排序键只能被调用一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!