Sorting in Python

Source: Internet
Author: User

Today, in http://www.pythontip.com, I encountered a sort of problem: a list of both strings, and numbers, how to sort.

List = [1,2,5,4,'d','s','e', 45 ]list.sort ()

If you call the sort () function directly, you will be quoted

TypeError                                 Traceback (most recent call last) in <module>()----> 1'<  ' not'str'and'int' 

I understand that the sort () function internally is a comparison of size by ' < ', and ' < ' does not support comparisons between strings and numbers.

Later we found a sorted () function to solve the sorting problem with strings and numbers

New_list = sorted (list)

Sorted () is not the same as sort (), sorted () is to sort the list as a parameter, and then get the sorted list, and sort () is sorted on the basis of the original list.

The sort () function is defined only in the list, and sorted () is valid for all iteration objects.

Use Help () to see the difference between the two:

---------------------------------Sorted----------------------------------------

in [+]: Help (List.sort)
Help on built-in function sort:

Sort (...) method of Builtins.list instance
L.sort (Key=none, Reverse=false), None--stable sort *in place*

--------------------------------Sorted---------------------------------------

In [All]: Help (sorted)
Help on built-in function sorted in module Builtins:

Sorted (iterable,/, *, Key=none, Reverse=false)
Return a new list containing all items from the iterable in ascending order.

A Custom key function can be supplied to customize the sort order, and the
Reverse flag can is set to request the result in descending order.

Ascending returns a new list that contains the iterations for all items.

You can provide a custom key function to customize the sort order, and you can set a reverse flag to return the results in descending order.

Sorting in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.