How to use sorted in Python () and sort () function

In a way, all programmers must write code for a project or sort the data. In the application of them, sequencing the user experience is very important, whether it is based on the time stamp on the recent activities of the user to sort, arrange or email list alphabetically by last name. Python's sorting function is very powerful and can perform basic or custom sorting to sort on the level of granularity.

In this tutorial, you will learn how to sort custom sorting and for a variety of data types in different data structures, and the use of two different sorting methods in Python.

At the end of this tutorial, you will know how to:

1, completing the basic data structure of a sort on Python

2, distinguished sorted () and .sort () function

3, based on the particular requirements of a sophisticated custom ordered in the coding

For the purposes of this tutorial, you need to list a set of tuples and have a basic understanding. In this tutorial, these data structures will be used, and will perform some basic operations on these data structures. Moreover, this tutorial using version Python3, so if you are using a version Python2 output sample might be slightly different.

Use sorted () function ordering

Before you start using Python sort, first you have to learn how to sort numeric and string data.

Sort numeric values

You can use Python in sorted () function to sort a list. In this embodiment, we define a list of integers, then calls sorted () function, variable numbers sorted as a function of parameters ().

How to use sorted in Python () and sort () function

 

The output is a new, ordered list. When printing the original variables, we can see that the initial value has not changed.

This example shows sorted important features () function are four:

1.sorted () function is not defined. It is a built-in function, can be used in standard Python installation.

2. In the case where no additional parameter, the sorted () function are arranged in ascending order of values, i.e. in ascending order.

3. The original numbers will not change, since the sorted () function provides a new ordered output, and does not change the order of the original value.

4. When sorted () function is called, it will provide an ordered list as a return value.

The last point means that the list can use the sorted () function, and the output can be assigned immediately to a variable:

How to use sorted in Python () and sort () function

 

In this example, a new variable is stored numbers_sorted sorted (output function).

You can view sorted by calling the help () function () function to verify that all of these observations. The reverse key and optional parameters later in this tutorial:

How to use sorted in Python () and sort () function

 

Technical details: If you are transitioning from Python2 to Python3, and its function is very familiar with the same name, you should pay attention to several important changes in the Python3:

1.Python3 in sorted () function does not cmp parameter. Instead, only the key parameter used to introduce custom sorting logic.

2.key must be passed as a parameter and reverse, which Python2 different, they can be passed as parameters Python2 in position.

If you need to convert Python2 the cmp function key function, see functools.cmp_to_key (). This tutorial will not cover any of the examples use Python2.

Tuples and can also use a set of sorted () function:

How to use sorted in Python () and sort () function

 

It is noteworthy that even a set of tuples input and output result is still a list, since sorted () function returns a new list definition. If the returned objects need to match the input type, it can be converted to the new type. If you try to convert the result back to the list of collection types, please note that, by definition, the sets are unordered:

How to use sorted in Python () and sort () function

 

As we expected the same results when the results lists into a collection, numbers_set_sorted are unordered. Other variables, such as numbers_tuple_sorted retained sorted order.

Sorting strings

str similar to other types of ordering iterables like lists and tuples. The following example shows the sorted () how to traverse function passed to it, and the value of each character in the character sort output:

How to use sorted in Python () and sort () function

 

sorted () function as a str a list, and wherein each element of the traverse. In one str, each element corresponds to a character in str. sorted () function in the same way to treat each sentence, it would sort each character including spaces.

.split () can change the result and clean output, .join () can be connected together again all the contents. We will briefly output and why is this particular order:

How to use sorted in Python () and sort () function

 

In the present embodiment, the original sentence is converted into a list of words and not as a str. Then, the list is sorted and combined to form a list instead of a str again.

Python sort of limitations and pitfalls

It is noteworthy that, when you use Python for non-integer values ​​of type sort may be some restrictions and strange results.

Containing the list of data types are not comparable unusable sorted () function

Some data types can not use the sorted () function compared with each other, because they are too different. If you try to use a sorted list can not contain comparative data type () function, Python will return an error. Which in the present embodiment, the same list None int can not be sorted and, because they are incompatible:

How to use sorted in Python () and sort () function

 

This error explains why Python is not given values ​​are sorted. It attempts to use less-than operator (<) to determine which value is lower, so that the value in sequence.

How to use sorted in Python () and sort () function

 

When you try to compare two values ​​are not comparable without using sorted () function, Python will throw the same type of error.

If the value list can compare and does not throw the wrong type, then the list can be sorted. This may prevent the iterative sort value has not sorted in nature, and may generate an output meaningless.

For example, the number 1 should be placed before the word apple do, however, if a iterable contains a combination of integers and strings, and they are all digital, you can use the list to convert them to a data type comparable?:

How to use sorted in Python () and sort () function

 

Each mixed_numbers elements called int () function, may be converted to any value str int value. Then, call the sorted () function can compare the success of each element, and a sort of produce a result.

Python may also be converted implicitly to the value of another type. In the following example, 1 <= 0 the value is False, the output result is False. As Boolean type, number 1 can be converted to True, the number 0 can be converted to False.

Even if the elements appear in the list are not the same, but they can be converted to a Boolean value (True or False), and using the sorted () function compared with each other:

How to use sorted in Python () and sort () function

 

'A'=='B'和1<=0都被转化为了布尔值False,并且返回了一个有序的输出结果。

这个例子说明了一个排序的重要方面:排序稳定性。在Python当中,当你对相等的值进行排序时,它们将会在输出时保留原本的顺序。即使移动了1的位置,所有其他的值都是相等的,因此它们保持了相对于彼此的原始顺序。在下面的例子中,所有的值都是相等的,并且将会保持它们原本的位置:

How to use sorted in Python () and sort () function

 

如果你观察原始的顺序和输出的顺序,你将会发现1 == 2被转化成了False,并且所有排序后的输出都与原始顺序相同。

当你对字符串排序时,大小写很重要

sorted()函数可以按照升序对字符串列表的值进行排序,默认情况下按照字母顺序:

How to use sorted in Python () and sort () function

 

然而,Python使用每个字符串中第一个字母的Unicode数值来确定升序排序顺序。这意味着sorted()函数不会将名称AL和al看作是一样的。本例将会使用ord()函数返回每个字符串中第一个字母的Unicode数值:

How to use sorted in Python () and sort () function

 

name[0]会返回sorted(names_with_case)中每一个元素的第一个字符,ord()会提供其Unicode数值。即使在字母表中a在M之前,但是M的Unicode数值在a之前,所以排序的结果是M在前。

如果第一个字母是相同的,那么sorted()将使用第二个字符来确定顺序,如果第二个字符是相同的,将会使用第三个字符,以此类推,直到字符串的末尾:

How to use sorted in Python () and sort () function

 

除了最后一个字符外,very_similar_strs的每一个字符都是相同的。使用sorted()函数比较字符串时,由于前五个字符都是相同的,所以输出结果将会根据第六个字符的值来判断。

包含相同值的字符串最终的顺序为从短到长,这是由于较短的字符串没有可以与较长字符串相比较的元素:

How to use sorted in Python () and sort () function

 

最短的字符串'h'在第一位,最长的字符串'hhhhh'在最后一位。

使用含有reverse参数的sorted()函数

正如sorted()函数的help()文档所示,有一个可选的参数reverse,它将根据分配给它的布尔值改变排序。如果reverse = True,那么就会按照降序排列:

How to use sorted in Python () and sort () function

 

排序的逻辑仍然保持不变,这意味着这些名字仍然按照第一个字母排序,但是因为reverse关键字被设置为True,所以输出结果的顺序是相反的。

当reverse关键字设置为False时,顺序将保持升序。之前的任何例子都可以用来检查reverse关键字设置True或Fasle后的结果:

How to use sorted in Python () and sort () function

 

使用含有key参数的sorted()函数

参数key是sorted()函数最强大的组成部分之一。这个参数可以接收一个函数,该函数将作用于排序列表中的每个值,以确定结果的顺序。

以一个简单的例子为例,对一个特定的列表进行排序,我们假设列表中字符串的长度为排序的要求,由短到长。参数key被设置为len()函数,len()函数的功能是返回一个字符串的长度:

How to use sorted in Python () and sort () function

 

最后的结果是一个按字符串顺序从短到长的列表。列表中每个元素的长度是由len()函数确定的,然后按照升序返回。

让我们回到前面的例子,按照第一个字母排序,当出现大小写不同的情况时,key可以通过将整个字符串转换成小写来解决这个问题:

How to use sorted in Python () and sort () function

 

输出值没有被转化为小写,这是因为参数key并没有处理原始列表中的数据。在排序过程中,将对每个元素调用key函数来确定排序顺序,但是输出的仍是原始值。

当使用带有参数key的函数时,有两个主要限制。

第一,传递给key的函数中所需参数的数量必须为1。

下面的例子说明了加法函数的定义,它需要两个参数。当加法函数作为参数key作于用一个数值列表时,它并不能发挥作用,因为它缺少第二个参数。在排序过程中每次调用add()函数,它每次只从列表中接收一个元素:

How to use sorted in Python () and sort () function

 

第二个限制是,带有key的函数必须能够处理迭代序列中的所有值。例如,你有一个以字符串形式表示的数值列表,要对其使用sorted()函数,参数key试图使用int()函数将它们转化为数字。如果迭代序列中的值不能转换为整数,那么该函数将无法产生作用:

How to use sorted in Python () and sort () function

 

每个作为str的数值都可以转换为int,但是four不行。这会引起一个ValueError,其错误解释为four不能被转化为整形,因为它是无效的。

参数key的功能非常强大,因为几乎所有函数,无论是内置函数还是用户自定义函数,都可以用来控制输出顺序。

如果排序要求是按照每个字符串的最后一个字母对可迭代序列进行排序(如果最后一个字母是相同的,就使用倒数第二个字母),那么就可以定义一个函数用来排序。下面的例子定义了一个函数,其功能是反转字符串序列,然后将该函数作为参数传递给key:

How to use sorted in Python () and sort () function

 

word[::-1]用于反转字符串。reverse_word()将会作用于每一个元素,而且排列顺序将会取决于最后的字符。

你可以在参数中定义lambda函数来代替编写一个独立的函数。

lambda函数是一个匿名函数:

1.必须是内联定义

2.没有名称

3.不能包含语句

4.像函数一样执行

在下面的例子中,参数key被设置为一个没有名称的lambda函数,lambda的参数是x,x[::-1]是对参数执行的操作:

How to use sorted in Python () and sort () function

 

对每个元素调用x[::-1]并反转单词。反转后的单词被用于排序,但是返回的仍然是原始的单词。

如果需求发生了变化,并且顺序也应该颠倒,那么reverse关键字可以和key参数一起使用:

How to use sorted in Python () and sort () function

 

当你需要根据属性对类对象排序时,lambda函数也很有用。如果你有一组学生,需要根据他们的最终成绩按照从高到低的顺序对他们进行排序,那么lambda可以用来从类中获取grade属性:

How to use sorted in Python () and sort () function

 

lambda在每个元素上调用getattr()函数并返回grade的值。

将reverse设置为True,使升序输出变为为降序输出,以便使成绩最高的排在第一位。

当你同时使用sorted()函数中的key和reverse参数时,如何实现排序的可能性是无穷无尽的。当你为一个小函数使用基本lambda式时,代码可以保持简短和整洁,或者你可以编写一个全新的函数,导入它,并在key参数中使用它。

使用.sort()对值排序

名称非常相似的.sort()与内置的sorted()有很大的差别。它们或多或少得完成了相同的事情,但是list.sort()的help()文档强调了二者之间最重要的两个区别:

How to use sorted in Python () and sort () function

 

第一,sort是list类的一个方法,只能与list一起使用。它不是一个内置的迭代器。

第二,.sort()返回None并改变值的位置。让我们看一下这两种代码差异的影响:

How to use sorted in Python () and sort () function

 

在这个代码示例中,.sort()与sorted()的操作方式有一些非常显著的差异:

1..sort()没有有序的输出,因此对新变量的赋值只传递None类型

2.values_to_sort列表的顺序已经发生了改变,而且原始顺序也并没有以任何形式保留下来。

这些行为上的差异使得.sort()和sorted()在代码中绝对不可互换,如果以错误的方式使用它们,可能会产生意想不到的结果。

.sort()具有与sorted()相同的key和reverse这种可选的关键字参数,这些参数具有与sorted()相同的强大的功能。在这里,你可以根据第三个单词的第二个字母对短语列表进行排序,然后逆序返回列表:

How to use sorted in Python () and sort () function

 

在本例当中,lambda函数被用来完成以下功能:

1.把每个短语分成一个单词列表

2.找到本例中的第三个元素或单词

3.找到第三单词中的第二个字母

何时使用sorted()和.sort()

你已经看到了sorted()和.sort()之间的区别,但是什么时候该用哪一个呢?

让我来说一下,有一个5k比赛即将到来:第一届年度Python 5k。需要捕获并排序来自比赛的数据。需要捕获的数据是跑步者的号码和完成比赛所需的秒数:

How to use sorted in Python () and sort () function

 

当参赛者跨过终点线时,每一个Runner都会被加入一个名为runners的列表当中。在5k比赛中,并不是所有的运动员都同时跨过起跑线,所以第一个越过终点线的人可能并不是最快的:

How to use sorted in Python () and sort () function

 

每一次一个跑步者跨过终点线,他们的号码以及耗时(以秒为单位)都会被加入到runners列表当中。

现在,负责处理结果数据的程序员看到了这个列表,知道了前5名最快的选手是获奖者,其余的参赛者将按时间排序。

You need not be ordered according to a plurality of types of different attributes. The size of this list is reasonable. The list does not mention stored somewhere. Simply press the time to sort, to find the fastest total time of five players:

How to use sorted in Python () and sort () function

 

Selected by the programmer to use the parameter in the function key lambda, their duration in order to obtain properties from each runner, and the use .sort () to sort the list of runners. After completion of sorting the list of runners, the first five elements are stored in a list top_five_runners.

Mission accomplished! Tournament director came to tell the programmer, because the current version of Python 3.7, so they decided to cross the finish line every 37 people will get a free gym bag.

At this time, programmers began to feel very upset, because the list of runners has been irreversibly changed, there is no way to restore the original order of the list of runners and found 37 per person.

If you are dealing with important data, even if the likelihood of these raw data needs to be restored is small, then the .sort () is not the best option. If the data is a copy, if it is not important operating data, if no one mind losing it, because it can be retrieved, so .sort () is a good choice.

Alternatively, the list may be used Runners sorted () function is ordered, and the same lambda expression:

How to use sorted in Python () and sort () function

 

Using sorted () function of this program, the original list of runners is still intact, is not covered. Through interaction with the original value, may be implemented every 37 reaches the finish line of temporary requirements:

How to use sorted in Python () and sort () function

 

every_thirtyseventh_runners list is to use a list slice syntax to create a list of runners, it still contains the original order of the runners crossed the finish line.

How to use Python Sort: Conclusion

.sort () and sorted () can provide the required sort order, if you use them correctly with the optional keyword arguments reverse and key words.

When it comes to output and modify data, both of which have very different characteristics, so make sure that any application function or program that you carefully considered the use .sort (), because it will irreversibly overwrite the data.

For enthusiastic challenge of finding terms of the sort of Python master, you can try to use more complex data types in the ordering: Nested iterator.

Guess you like

Origin blog.csdn.net/java276582434/article/details/90812971