添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

The sort codebase (used by both sorted() and list.sort() works exclusively with list object, and is geared towards sorting python objects ; items that can implement custom special methods that dictate ordering.

As such, that code is not readily reusable for the array.array and bytearray types, which deal exclusively in homogenous C type data.

Instead, you'd need to implement a dedicated sorting method for these types, taking advantage of the fact you are basically dealing with basic C types here. And no one has done this yet, which is really the only reason these types have no dedicated .sort() methods.

The work-around is to use sorted() and re-cast as the original type:

a = array.array(a.typecode, sorted(a))
b = bytearray(sorted(b))

The numpy ndarray type does have a .sort() method; perhaps you should use that library instead if you need to do a lot of sorting.

Excellent answer! I was looking for the Python core developer perspective and that's what you gave us. Thank you very much, Martijn! – Luciano Ramalho Apr 1, 2014 at 10:54

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.