Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

sorting - Are python sort keys guaranteed to be called only once?

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.

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?

The documentation of sorted states:

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)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the section of the docs you link:

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.

That would seem to be a "yes" ...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...