python排序冒泡排序_python排序的终极指南

python排序冒泡排序

In this tutorial, we will look at how to sort iterables, such as lists, tuples, strings, and dictionaries, based on different criteria.

在本教程中,我们将研究如何基于不同的条件对可迭代对象(例如列表,元组,字符串和字典)进行排序。

排序列表 (Sorting a List)

There are two ways to sort a list. We can either use the sort() method or the sorted() function. The sort() method is a list method and thus can only be used on lists. The sorted() function works on any iterable.

有两种方式对列表进行排序。 我们可以使用sort()方法或sorted()函数。 sort()方法是一个列表方法,因此只能在列表上使用。 sorted()函数可用于任何迭代。

sort()方法 (sort() method)

The sort() method is a list method that modifies the list in-place and returns None. In other words, the sort() method modifies or changes the list it is called on, and does not create a new list.

sort()方法是一个列表方法,它就地修改列表并返回None。 换句话说,sort()方法会修改或更改被调用的列表,并且不会创建新列表。

The sort() method has two optional parameters: the key parameter and reverse parameter. The key parameter takes in a function that takes a single argument and returns a key to use for sorting. By default, the sort() method will sort a list of numbers by their values and a list of strings alphabetically. The reverse parameter accepts a boolean value of True or False. The default value for reverse is False, meaning it sorts in ascending order. To sort in descending order, we would set reverse=True. These parameters will make much more sense as we look at some examples below.

sort()方法有两个可选参数:key参数和reverse参数。 key参数接受一个带有单个参数的函数,并返回用于排序的键。 默认情况下,sort()方法将按数值对数字列表和按字母顺序对字符串列表进行排序。 reverse参数接受布尔值True或False。 反向的默认值为False,表示它以升序排序。 为了按降序排序,我们将设置reverse = True。 当我们看下面的一些示例时,这些参数将更有意义。

对数字列表进行排序 (Sorting a List of Numbers)

Let’s say that we have a list of numbers and we want to sort it in ascending order.

假设我们有一个数字列表,我们想按升序对其进行排序。

num_list = [1,-5,3,-9,25,10]num_list.sort()print(num_list)
# [-9,-5,1,3,10,25]

So we have a list of numbers, or num_list. We call the sort() method on this list. Notice how we didn’t pass in a value for the key parameter. Thus, it just sorted this list of numbers by their actual values. And since we didn’t set reverse = True, it sorted in ascending order. The sort() method modified our num_list.

因此,我们有一个数字列表或num_list。 我们在此列表上调用sort()方法。 请注意,我们如何不传递key参数的值。 因此,它只是按照数字的实际值对该数字列表进行排序。 而且由于我们没有设置reverse = True,所以它以升序排列。 sort()方法修改了我们的num_list

What if we want to sort our list based on the absolute values of the numbers? That is when we would need to use the key parameter. The key parameter takes in a function that takes a single argument and returns a key to use for sorting.

如果我们想根据数字的绝对值对列表进行排序怎么办? 那就是我们需要使用key参数的时候。 key参数接受一个带有单个参数的函数,并返回用于排序的键。

num_list = [1,-5,3,-9,25,10]def absolute_value(num):
return abs(num)num_list.sort(key = absolute_value)print(num_list)
# [1,3,-5,-9,10,25]

We defined a function, absolute_value, that takes in a number and returns its absolute value. We then passed this function in as the argument for the key parameter of the sort() method. Thus, it runs each element or number of num_list through the absolute value function before it makes the comparison. As a result, the absolute values of the numbers are used to sort this list in ascending order (since reverse is set to False by default).

我们定义了一个函数absolute_value ,该函数接受一个数字并返回其绝对值。 然后,我们将此函数作为sort()方法的key参数的参数传入。 因此,它会在进行比较之前通过绝对值函数运行num_list的每个元素或编号。 结果,数字的绝对值用于按升序对该列表进行排序(因为默认情况下将reverse设置为False)。

使用lambda表达式 (Using a lambda expression)

We could have passed in a lambda expression instead for the key parameter as follows:

我们可以传递lambda表达式来代替key参数,如下所示:

num_list.sort(key = lambda num: abs(num))

Check out the tutorial on lambda expressions here:

在此处查看有关lambda表达式的教程:

Remember that the sort() method returns None. Thus, if we set the output, or return value, of the sort() method to a new variable, we get None as follows:

请记住,sort()方法返回None。 因此,如果将sort()方法的输出或返回值设置为新变量,则将得到None,如下所示:

new_list = num_list.sort(key = absolute_value)print(new_list)
# None

使用内置功能 (Using built-in functions)

Instead of writing our own absolute_value function as we did above, we could have just passed in the python built-in abs() function for the key parameter as follows:

与其像上面那样编写我们自己的absolute_value函数,不如直接将python内置的abs()函数传递给key参数,如下所示:

num_list.sort(key = abs)

sorted()函数 (sorted() function)

The sorted() function can accept three parameters: the iterable, the key, and reverse. In other words, the sort() method only works on lists, but the sorted() function can work on any iterable, such as lists, tuples, dictionaries, and others. However, unlike the sort() method which returns None and modifies the original list, the sorted() function returns a new list while leaving the original object unchanged.

sorted()函数可以接受三个参数:可迭代,键和反向。 换句话说,sort()方法仅适用于列表,但是sorted()函数可以适用于任何可迭代的对象,例如列表,元组,字典等。 但是,与sort()方法返回None并修改原始列表的方法不同,sorted()函数返回一个新列表,同时保持原始对象不变。

Let’s sort num_list again using the absolute values but using the sorted() function instead:

让我们再次使用绝对值对num_list进行排序,但改用sorted()函数:

num_list = [1,-5,3,-9,25,10]new_list = sorted(num_list, key = abs)print(new_list) 
# [1,3,-5,-9,10,25]print(num_list)
# [1,-5,3,-9,25,10]

We pass in the iterable, num_list, to the sorted() function, along with the built-in abs function to the key parameter. We set the output of the sorted() function to a new variable, new_list. Note how num_list is unaltered since the sorted() function does not modify the iterable it acts on.

我们将可迭代的num_list传递给sorted()函数,并将内置的abs函数传递给key参数。 我们将sorted()函数的输出设置为新变量new_list 。 请注意num_list是如何不变的,因为sorted()函数不会修改其作用的可迭代性。

Note: No matter what iterable is passed in to the sorted() function, it always returns a list.

注意:无论将什么可迭代传递给sorted()函数,它总是返回一个列表。

对元组列表进行排序 (Sorting a List of Tuples)

Let’s say that we have a list of tuples. Each element of the list is a tuple that contains three elements: the name, age, and salary.

假设我们有一个元组列表。 列表的每个元素都是一个包含三个元素的元组:名称,年龄和薪水。

list_of_tuples = [
('john', 27, 45000),
('jane', 25, 65000),
('beth', 31, 70000)
]

We can sort this list alphabetically, by age, or by salary. We can specify which we want to use with the key parameter.

我们可以按字母顺序,年龄或薪水对列表进行排序。 我们可以通过key参数指定要使用的参数。

To sort by age, we can use the following code:

要按年龄排序,我们可以使用以下代码:

sorted_age_list = sorted(list_of_tuples, key = lambda person: person[1])print(sorted_age_list) 
# [('jane', 25, 65000), ('john', 27, 45000), ('beth', 31, 70000)]

Each element of the list_of_tuples is passed in to the lambda function as the person parameter. The element at index 1 of each tuple is returned. That is the value that is used to sort the list, which is the age.

list_of_tuples的每个元素都作为person参数传递给lambda函数。 返回每个元组的索引1处的元素。 这是用于对列表进行排序的值,即年龄。

To sort the name alphabetically, we can do so without passing a key at all since by default the first element of each tuple is what is compared (and remember, by default, strings are sorted alphabetically):

要按字母顺序对名称进行排序,我们可以完全不传递键,因为默认情况下,每个元组的第一个元素是要进行比较的内容(请记住,默认情况下,字符串按字母顺序进行排序):

sorted_name_list = sorted(list_of_tuples)print(sorted_name_list) 
# [('beth', 31, 70000), ('jane', 25, 65000), ('john', 27, 45000)]

However, we can specify that we want to sort by the first element of each tuple as follows:

但是,我们可以指定我们要按每个元组的第一个元素进行排序,如下所示:

sorted_name_list = sorted(list_of_tuples, key = lambda person: person[0])print(sorted_name_list) 
# [('beth', 31, 70000), ('jane', 25, 65000), ('john', 27, 45000)]

Remember that we can assign a lambda expression to a variable (similar to using the def keyword to define a function). Thus, we can organize the lambda expressions based on the criteria they use to sort the list:

请记住,我们可以将lambda表达式分配给变量(类似于使用def关键字定义函数)。 因此,我们可以根据lambda表达式对列表进行排序的标准来组织它们:

name = lambda person: person[0]
age = lambda person: person[1]
salary = lambda person: person[2]# sort by name
sorted(list_of_tuples, key = name)# sort by age
sorted(list_of_tuples, key = age)# sort by salary
sorted(list_of_tuples, key = salary)

itemgetter()函数 (itemgetter() function)

Instead of using a lambda expression to access the name, age, or salary elements from the tuples, we can instead use the itemgetter() function that is available in the operator module. We can specify which element to access in the tuple by passing in the index. Each tuple of the list is passed in to the itemgetter() function, and the specific element from that tuple is returned based on the index specified.

我们可以使用运算符模块中可用的itemgetter()函数代替使用lambda表达式访问元组的名称,年龄或薪水元素。 我们可以通过传入索引来指定要在元组中访问的元素。 列表中的每个元组都传递到itemgetter()函数中,并且基于指定的索引返回该元组中的特定元素。

import operator# sort by name
sorted(list_of_tuples, key = operator.itemgetter(0))# sort by age
sorted(list_of_tuples, key = operator.itemgetter(1))# sort by salary
sorted(list_of_tuples, key = operator.itemgetter(2))

The itemgetter() function allows multiple levels of sorting. For example, let’s say we had this list of tuples instead:

itemgetter()函数允许进行多个级别的排序。 例如,假设我们有以下元组列表:

list_of_tuples = [
('john', 27, 45000),
('jane', 25, 65000),
('joe', 25, 35000),
('beth', 31, 70000)
]

Notice how jane and joe both have the same age. So if we wanted to sort this list by age first, and by salary second, we can pass in two values to the itemgetter() function:

注意简和乔的年龄相同。 因此,如果我们想按年龄先对列表进行排序,然后按薪水对列表进行排序,则可以将两个值传递给itemgetter()函数:

print(sorted(list_of_tuples, key=operator.itemgetter(1,2))# [('joe', 25, 35000), ('jane', 25, 65000), ('john', 27, 45000), ('beth', 31, 70000)]

Since the index for age is the first value passed in, that will be used to sort the elements first. If the age is the same, salary will be used to order the elements.

由于age的索引是传入的第一个值,因此将用于首先对元素进行排序。 如果年龄相同,将使用薪水对要素进行排序。

Note: The operator module also has the attrgetter() function that can be used to sort objects with named attributes. For example, if we wrote our own class and instantiated objects of that class, we can order those objects using a specific named attribute by using the attrgetter() function. We would just pass in the name of the attribute to the attrgetter() function, and then pass that function into the key parameter of the sorted() function. For example, to order the objects by age, we would pass in the following to the key parameter: key = attrgetter(‘age’).

注意:操作员模块还具有attrgetter()函数,该函数可用于对具有命名属性的对象进行排序。 例如,如果我们编写了自己的类和该类的实例化对象,则可以使用attrgetter()函数使用特定的命名属性对这些对象进行排序。 我们只是将属性的名称传递给attrgetter()函数,然后将该函数传递给sorted()函数的关键参数。 例如,要按年龄对对象进行排序,我们将以下内容传递给key参数:key = attrgetter('age')。

对元组进行排序 (Sorting a Tuple)

Sorting a tuple will be the same as sorting a list with the sorted() function as seen earlier. We cannot use the sort() method because it is a list method. Furthermore, since tuples are immutable objects, it would make sense that we cannot use the sort() method, since the sort() method modifies the original list.

对元组进行排序与​​使用sorted()函数对列表进行排序相同。 我们不能使用sort()方法,因为它是一个列表方法。 此外,由于元组是不可变的对象,因此有理由说我们不能使用sort()方法,因为sort()方法会修改原始列表。

Remember, even if we pass in a tuple to the sorted() function, a list is returned.

请记住,即使我们将元组传递给sorted()函数,也会返回一个列表。

num_tuple = (5,2,53,9,25)sorted_tuple = sorted(num_tuple)print(sorted_tuple)
# [2,5,9,25,53]

字符串排序 (Sorting a String)

Strings are iterables. Thus, they can also be sorted using the sorted() function. The sorted() function will iterate over the string, character by character. By default, the sorted() function will sort the string in alphabetical order.

字符串是可迭代的。 因此,也可以使用sorted()函数对它们进行排序。 sorted()函数将逐个字符地遍历字符串。 默认情况下,sorted()函数将按字母顺序对字符串进行排序。

sorted_string = sorted(‘dinosaur’)print(sorted_string)
# ['a','d','i','n','o','r','s','u']

Notice how the sorted() function returns a list of the characters in alphabetical order.

请注意sorted()函数如何以字母顺序返回字符列表。

字典排序 (Sorting a Dictionary)

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

字典由键:值对组成。 因此,可以通过键或值对它们进行排序。

Let’s say that we have a dictionary, with the keys being names, and the values being ages.

假设我们有一个字典,键是名称,值是年龄。

dictionary_of_names = {'beth': 37, 
'jane': 32,
'john': 41,
'mike': 59
}

If we just pass in the entire dictionary as the iterable to the sorted() function, we will get the following output:

如果我们仅将整个字典作为迭代器传递给sorted()函数,则将获得以下输出:

print(sorted(dictionary_of_names))
# ['beth', 'jane', 'john', 'mike']

As we can see, if we pass in the entire dictionary as the iterable to the sorted() function, it returns a list that contains only the keys sorted alphabetically.

如我们所见,如果我们将整个字典以可迭代的方式传递给sorted()函数,它将返回仅包含按字母顺序排序的键的列表。

使用items()方法 (Using the items() method)

If we want to get a sorted copy of the entire dictionary, we need to use the dictionary items() method:

如果要获取整个字典的排序副本,则需要使用字典items()方法:

print(dictionary_of_names.items())
# dict_items([('beth', 37), ('jane', 32), ('john', 41), ('mike', 59)])

Notice how the items() method returns a dict_items object, which looks similar to a list of tuples. This dict_items object is an iterable. Thus, it can be passed in as the iterable to the sorted() function.

注意,items()方法如何返回一个dict_items对象,该对象看起来类似于元组列表。 此dict_items对象是可迭代的。 因此,它可以迭代形式传递给sorted()函数。

We can sort this dict_items object the same way we sorted the list of tuples seen earlier. For example, to sort by the second element in each tuple, which would be the age, we can use the following code:

我们可以像对前面看到的元组列表进行排序一样,对dict_items对象进行排序。 例如,要按每个元组中的第二个元素(即年龄)进行排序,我们可以使用以下代码:

sorted_age = sorted(dictionary_of_names.items(), key = lambda kv: kv[1])print(sorted_age)
# [('jane', 32), ('beth', 37), ('john', 41), ('mike', 59)]

Notice how the sorted() function returns a list of tuples, sorted by the age (or second element in each tuple). To convert this list of tuples into a dictionary, we can use the built-in dict() function:

注意sorted()函数如何返回元组列表,并按年龄(或每个元组中的第二个元素)排序。 要将这个元组列表转换成字典,我们可以使用内置的dict()函数:

sorted_dictionary = dict(sorted_age)print(sorted_dictionary)
# {'jane': 32, 'beth': 37, 'john': 41, 'mike': 59}

Now we have a dictionary sorted by age!

现在我们有了按年龄排序的字典!

结论 (Conclusion)

In this tutorial, we compared the sort() method and sorted() function when sorting a list. We learned how the sort() method modifies the original list, and the sorted() function returns a new list. We also learned that the sort() method only works on lists, but the sorted() function can work on any iterable. We then learned how to sort different types of iterables and using different criteria.

在本教程中,我们在对列表进行排序时比较了sort()方法和sorted()函数。 我们学习了sort()方法如何修改原始列表,并且sorted()函数返回了一个新列表。 我们还了解到sort()方法仅适用于列表,但sorted()函数可适用于任何可迭代的对象。 然后,我们学习了如何对不同类型的可迭代对象进行排序以及如何使用不同的标准。

翻译自: https://towardsdatascience.com/the-ultimate-guide-to-sorting-in-python-d07349fb96d5

python排序冒泡排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值