精华内容
下载资源
问答
  • As part of a python assignment I'm trying to implement list sorting (ascending) without using the sort() method, I think my logic is correct but I keep getting an error:sample=[23,44,12,1,6,87]temp=0f...

    As part of a python assignment I'm trying to implement list sorting (ascending) without using the sort() method, I think my logic is correct but I keep getting an error:

    sample=[23,44,12,1,6,87]

    temp=0

    for i in range(0,len(sample)):

    if sample[i] > sample[i+1]:

    sample[i]=temp

    sample[i]=sample[i+1]

    sample[i+1]=temp

    This keeps giving me a list: index out of range error which I know is being caused by the fact that when the i == 3 the code still does i+1.

    Need help with this..

    I changed the code to:

    for i in range(0,len(sample)-1):

    if sample[i] > sample[i+1]:

    temp=sample[i]

    sample[i]=sample[i+1]

    sample[i+1]=temp

    that eliminates the error but doesn't sort the list

    解决方案

    python bubble sorting:

    sample=[23,44,12,1,6,87]

    sorted = False

    while not sorted:

    sorted = True

    for i in range(len(sample) - 1):

    if sample[i] > sample[i+1]:

    sorted = False

    sample[i], sample[i+1] = sample[i+1], sample[i]

    print sample

    展开全文
  • python升序和降序排序If you want to learn how to work with the sort() method in your Python projects, then this article is for you. This method is very powerful and you can customize it to fit your ...

    python升序和降序排序

    If you want to learn how to work with the sort() method in your Python projects, then this article is for you. This method is very powerful and you can customize it to fit your needs, so let's see how it works in detail.

    如果您想学习如何在Python项目中使用sort()方法,那么本文适合您。 此方法功能非常强大,您可以根据需要对其进行自定义,因此让我们详细了解它的工作原理。

    You will learn:

    您将学习:

    • How to use this method and customize its functionality.

      如何使用此方法并自定义其功能。
    • When to use it and when not to use it.

      何时使用和何时不使用它。
    • How to call it passing different combinations of arguments.

      如何通过不同的参数组合调用它。
    • How to sort a list in ascending and descending order.

      如何按升序和降序对列表进行排序。
    • How to compare the elements of a list based on intermediate values.

      如何基于中间值比较列表的元素。
    • How you can pass lambda functions to this method.

      如何将lambda函数传递给此方法。
    • How this method compares to the sorted() function.

      此方法与sorted()函数的比较。

    • Why the sort() method performs a stable sort.

      为什么sort()方法执行稳定的排序。

    • How the process of mutation works behind the scenes.

      突变过程如何在后台工作。

    Are you ready? Let's begin! ⭐

    你准备好了吗? 让我们开始! ⭐

    目的和用例 (Purpose and Use Cases)

    With the sort() method, you can sort a list in either:

    使用sort()方法,可以对以下任一列表进行排序:

    • Ascending Order

      升序
    • Descending Order

      降序

    This method is used to sort a list in place, which means that it mutates it or modifies it directly without creating additional copies, so remember:

    此方法用于对列表进行排序,这意味着它会对其进行突变或直接对其进行修改,而无需创建其他副本,因此请记住:

    You will learn more about mutation in this article (I promise!), but for now it's very important that you know that the sort() method modifies the list, so its original version is lost.

    您将在本文中了解有关突变的更多信息(我保证!),但是现在很重要的一点是,您知道sort()方法会修改列表,因此它的原始版本会丢失。

    Because of this, you should only use this method if:

    因此,仅在以下情况下才应使用此方法:

    • You want to modify (sort) the list permanently.

      您要永久修改(排序)列表。
    • You don't need to keep the original version of the list.

      您无需保留列表的原始版本。

    If this fits your needs, then the .sort() method is exactly what you are looking for.

    如果这符合您的需求,那么.sort()方法正是您想要的。

    🔸语法和参数 (🔸 Syntax and Arguments)

    Let's see how you can call .sort() to take advantage of its full power.

    让我们看看如何调用.sort()来利用其全部功能。

    This is the most basic call (with no arguments):

    这是最基本的调用(无参数):

    If you don't pass any arguments, by default:

    如果您不传递任何参数,则默认情况下:

    • The list will be sorted in ascending order.

      该列表将按升序排序。
    • The elements of the list will be compared directly using their values with the < operator.

      列表中的元素将使用其值与<运算符直接进行比较。

    For example:

    例如:

    >>> b = [6, 3, 8, 2, 7, 3, 9]
    >>> b.sort()
    >>> b
    [2, 3, 3, 6, 7, 8, 9] # Sorted!

    自定义参数 (Custom Arguments  )

    To customize how the sort() method works, you can pass two optional arguments:

    要自定义sort()方法的工作方式,可以传递两个可选参数:

    • Key

    • Reverse

      逆转

    Let's see how they change the behavior of this method. Here we have a method call with these two arguments:

    让我们看看它们如何更改此方法的行为。 这里有两个参数的方法调用:

    Before explaining how they work, I would like to explain something that you probably noticed in the diagram above – in the method call, the names of the parameters have to be included before their corresponding values, like this:

    在解释它们如何工作之前,我想解释一下您可能在上图中注意到的一些内容–在方法调用中,必须在参数的相应值之前包括参数名称,如下所示:

    • key=<f>

      key=<f>

    • reverse=<value>

      reverse=<value>

    This is because they are keyword-only arguments. If you are passing a custom value for them, their names have to be specified in the method call, followed by an equal sign = and their corresponding values, like this:

    这是因为它们是仅关键字的参数 。 如果要为它们传递自定义值,则必须在方法调用中指定它们的名称 ,后跟等号=及其对应的值,如下所示:

    Otherwise, if you try to pass the arguments directly as we normally do for positional parameters, you will see this error because the function will not know which argument corresponds to which parameter:

    否则,如果您尝试像通常对位置参数一样直接传递参数,则会看到此错误,因为函数将不知道哪个参数对应于哪个参数:

    TypeError: sort() takes no positional arguments

    逆转 (Reverse)

    Now that you know what keyword-only arguments are, let's start with reverse.

    现在您知道什么是仅关键字参数,让我们从reverse开始。

    The value of reverse can be either True or False:

    reverse的值可以为TrueFalse

    • False means that the list will be sorted in ascending order.

      False表示列表将按升序排序。

    • True means that the list will be sorted in descending (reverse) order.

      True表示列表将以降序(反向)排序。

    💡 Tip: By default, its value is False – if you don't pass any arguments for this parameter, the list is sorted in ascending order.

    💡 提示:默认情况下,其值为False –如果您不为此参数传递任何参数,则列表将按升序排序。

    Here we have a few examples:

    这里有一些例子:

    # List of Integers
    >>> b = [6, 3, 8, 2, 7, 3, 9]
    >>> b.sort()
    >>> b
    [2, 3, 3, 6, 7, 8, 9]
    
    # List of Strings
    >>> c = ["A", "Z", "D", "T", "U"]
    >>> c.sort()
    >>> c
    ['A', 'D', 'T', 'U', 'Z']

    💡 Tip: If the elements of the list are strings, they are sorted alphabetically.

    💡 提示:如果列表中的元素是字符串,则它们将按字母顺序排序。

    # List of Integers
    >>> b = [6, 3, 8, 2, 7, 3, 9]
    >>> b.sort(reverse=True)
    >>> b
    [9, 8, 7, 6, 3, 3, 2]
    
    # List of Strings
    >>> c = ["A", "Z", "D", "T", "U"]
    >>> c.sort(reverse=True)
    >>> c
    ['Z', 'U', 'T', 'D', 'A']

    💡 Tip: Notice how the list is sorted in descending order if reverse is True.

    💡 提示:请注意,如果reverseTrue则列表将按降序排序。

    (Key)

    Now that you know how to work with the reverse parameter, let's see the key parameter.

    现在您知道如何使用reverse参数,让我们来看一下key参数。

    This parameter is a little bit more detailed because it determines how the elements of the list are be compared during the sorting process.

    此参数稍微详细一点,因为它确定在排序过程中如何比较列表中的元素。

    The value of key is either:

    key的值是:

    • None, which means that the elements of the list will be compared directly. For example, in a list of integers, the integers themselves can be used for the comparison.

      None ,这意味着将直接比较列表中的元素。 例如,在整数列表中,整数本身可用于比较。

    • A function of one argument that generates an intermediate value for each element. This intermediate value is calculated only once and it's used to make the comparisons during the entire sorting process. We use this when we don't want to compare the elements directly, for example, when we want to compare strings based on their length (the intermediate value).

      一个参数 函数 ,为每个元素生成一个中间值。 该中间值仅计算一次,并在整个排序过程中用于进行比较。 当我们不想直接比较元素时,例如当我们要根据字符串的长度(中间值)比较字符串时,可以使用它。

    💡 Tip: By default, the value of key is None, so the elements are compared directly.

    💡 提示:默认情况下, key值为None ,因此可以直接比较元素。

    For example:

    例如:

    Let's say that we want to sort a list of strings based on their length, from the shortest string to the longest string. We can pass the function len as the value of key, like this:

    假设我们要根据字符串的长度(从最短的字符串到最长的字符串)对字符串列表进行排序。 我们可以将函数len作为key的值传递,如下所示:

    >>> d = ["aaa", "bb", "c"]
    >>> d.sort(key=len)
    >>> d
    ['c', 'bb', 'aaa']

    💡 Tip: Notice that we are only passing the name of the function (len) without parenthesis because we are not calling the function. This is very important.

    提示:请注意,由于我们没有调用函数,因此仅传递函数名称( len )而没有括号。 这个非常重要。

    Notice the difference between comparing the elements directly and comparing their length (see below). Using the default value of key (None) would have sorted the strings alphabetically (left), but now we are sorting them based on their length (right):

    注意直接比较元素和比较元素长度之间的区别(请参见下文)。 使用key的默认值( None )可以按字母顺序对字符串进行排序(左),但是现在我们根据字符串的长度(右)对其进行排序:

    What happens behind the scenes? Each element is passed as an argument to the len() function, and the value returned by this function call is used to perform the comparisons during the sorting process:

    幕后发生了什么? 每个元素都作为参数传递给len()函数,此函数调用返回的值用于在排序过程中执行比较:

    This results in a list with a different sorting criteria: length.

    这将导致列表具有不同的排序标准:长度。

    Here we have another example:

    这里有另一个例子:

    Another interesting example is sorting a list of strings as if they were all written in lowercase letters (for example, making "Aa" equivalent to "aa").

    另一个有趣的示例是对字符串列表进行排序,就好像它们都是用小写字母书写一样(例如,使“ Aa”等效于“ aa”)。

    According to lexicographical order, capital letters come before lowercase letters:

    根据字典顺序,大写字母先于小写字母:

    >>> "E" < "e"
    True

    So the string "Emma" would come before "emily" in a sorted list, even if their lowercase versions would be in the opposite order:

    因此,即使它们的小写版本的排列顺序相反,字符串"Emma"也将在排序列表中的"emily"之前出现:

    >>> "Emma" < "emily"
    True
    >>> "emma" < "emily"
    False

    To avoid distinguishing between capital and lowercase letters, we can pass the function str.lower as key. This will generate a lowercase version of the strings that will be used for the comparisons:

    为了避免区分大小写字母,我们可以将函数str.lower作为key传递。 这将生成将用于比较的字符串的小写版本:

    >>> e = ["Emma", "emily", "Amy", "Jason"]
    >>> e.sort(key=str.lower)
    >>> e
    ['Amy', 'emily', 'Emma', 'Jason']

    Notice that now, "emily" comes before "Emma" in the sorted list, which is exactly what we wanted.

    请注意,现在,已排序列表中的"Emma"之前是"emily" ,这正是我们想要的。

    💡 Tip: if we had used the default sorting process, all the strings that started with an uppercase letter would have come before all the strings that started with a lowercase letter:

    💡 提示:如果我们使用了默认的排序过程,则所有以大写字母开头的字符串都将排在所有以小写字母开头的字符串之前:

    >>> e = ["Emma", "emily", "Amy", "Jason"]
    >>> e.sort()
    >>> e
    ['Amy', 'Emma', 'Jason', 'emily']

    Here is an example using Object-Oriented Programming (OOP):

    这是使用面向对象编程(OOP)的示例:

    If we have this very simple Python class:

    如果我们有这个非常简单的Python类:

    >>> class Client:
    	def __init__(self, age):
    		self.age = age

    And we create four instances:

    我们创建了四个实例:

    >>> client1 = Client(67)
    >>> client2 = Client(23)
    >>> client3 = Client(13)
    >>> client4 = Client(35)

    We can make a list that references them:

    我们可以列出引用它们的列表:

    >>> clients = [client1, client2, client3, client4]

    Then, if we define a function to get the age of these instances:

    然后,如果我们定义一个函数来获取age这些实例:

    >>> def get_age(client):
    	return client.age

    We can sort the list based on their age by passing the get_age function an an argument:

    我们可以通过将参数get_age传递给参数来根据年龄对列表进行排序:

    >>> clients.sort(key=get_age)

    This is the final, sorted version of the list. We use a for loop to print the age of the instances in the order that they appear in the list:

    这是列表的最终排序版本。 我们使用一个for循环按照实例在列表中出现的顺序来打印实例的寿命:

    >>> for client in clients:
    	print(client.age)
    
    	
    13
    23
    35
    67

    Exactly what we wanted – now the list is sorted in ascending order based on the age of the instances.

    正是我们想要的-现在,列表根据实例的使用期限以升序排序。

    💡 Tip: Instead of defining a get_age function, we could have used a lambda function to get the age of each instance, like this:

    提示:我们可以使用lambda函数来获取每个实例的年龄,而不是定义get_age函数,如下所示:

    >>> clients.sort(key=lambda x: x.age)

    Lambda functions are small and simple anonymous functions, which means that they don't have a name. They are very helpful for these scenarios when we only want to use them in particular places for a very short period of time.

    Lambda函数是小型且简单的匿名函数,这意味着它们没有名称。 当我们只想在特定位置短时间使用它们时,它们对于这些情况非常有用。

    This is the basic structure of the lambda function that we are using to sort the list:

    这是我们用来对列表进行排序的lambda函数的基本结构:

    传递两个参数 (Passing Both Arguments)

    Awesome! Now you know to customize the functionality of the sort() method. But you can take your skills to a whole new level by combining the effect of key and reverse in the same method call:

    太棒了! 现在您知道了自定义sort()方法的功能。 但是您可以通过在同一方法调用中组合keyreverse key的效果,将您的技能提升到一个全新的水平:

    These are the different combinations of the arguments and their effect:

    这些是参数及其效果的不同组合:

    仅关键字参数的顺序不重要 (The Order of Keyword-Only Arguments Doesn't Matter)

    Since we are specifying the names of the arguments, we already know which value corresponds to which parameter, so we can include either key or reverse first in the list and the effect will be exactly the same.

    由于我们正在指定参数的名称,因此我们已经知道哪个值对应于哪个参数,因此我们可以在列表中首先包含keyreverse ,并且效果将完全相同。

    So this method call:

    所以这个方法调用:

    Is equivalent to:

    等效于:

    This is an example:

    这是一个例子:

    >>> a = ["Zz", "c", "y", "o", "F"]
    >>> a.sort(key=str.lower, reverse=True)
    >>> a
    ['Zz', 'y', 'o', 'F', 'c']

    If we change the order of the arguments, we get the exact same result:

    如果更改参数的顺序,则会得到完全相同的结果:

    >>> a = ["Zz", "c", "y", "o", "F"]
    >>> a.sort(reverse=True, key=str.lower)
    >>> a
    ['Zz', 'y', 'o', 'F', 'c']

    🔹返回值 (🔹 Return Value)

    Now let's talk a little bit about the return value of this method. The sort() method returns None – it does not return a sorted version of the list, like we might intuitively expect.

    现在让我们谈谈该方法的返回值。 该sort()方法返回None - 返回列表的排序版本,就像我们可以直观地期待。

    According to the Python Documentation:

    根据Python文档

    To remind users that it operates by side effect, it does not return the sorted sequence.
    为了提醒用户它是有副作用的,它不会返回已排序的序列。

    Basically, this is used to remind us that we are modifying the original list in memory, not generating a new copy of the list.

    基本上,这是用来提醒我们,我们正在修改内存中的原始列表,而不是生成列表的新副本。

    This is an example of the return value of sort():

    这是sort()返回值的示例:

    >>> nums = [6.5, 2.4, 7.3, 3.5, 2.6, 7.4]
    
    # Assign the return value to this variable:
    >>> val = nums.sort()
    
    # Check the return value:
    >>> print(val)
    None

    See? None was returned by the method call.

    看到? 方法调用None返回None

    💡 Tip: It is very important not to confuse the sort() method with the sorted() function, which is a function that works very similarly, but doesn't modify the original list. Instead sorted() generates and returns a new copy of the list, already sorted.

    提示:不要将sort()方法与sorted()函数混淆,这是一个非常相似的函数,但不会修改原始列表,这一点非常重要。 而是sorted()生成并返回已排序的列表的新副本。

    This is an example that we can use to compare them:

    这是一个我们可以用来比较它们的示例:

    This is very important because their effect is very different. Using the sort() method when you intended to use sorted() can introduce serious bugs into your program because you might not realize that the list is being mutated.

    这非常重要,因为它们的效果有很大不同。 当您打算使用sorted()时使用sort()方法可能会在程序中引入严重的错误,因为您可能没有意识到列表已被更改。

    (sort()方法执行稳定的排序 (🔸 The sort() Method Performs a Stable Sort)

    Now let's talk a little bit about the characteristics of the sorting algorithm used by sort().

    现在,让我们来谈谈sort()使用的排序算法的特征。

    This method performs a stable sort because it works with an implementation of TimSort, a very efficient and stable sorting algorithm.

    此方法执行稳定的排序,因为它与TimSort的实现(一种非常有效且稳定的排序算法)一起使用。

    According to the Python Documentation:

    根据Python文档

    A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

    如果可以保证不改变比较相等的元素的相对顺序,则排序是稳定的-这有助于多次通过排序(例如,按部门排序,然后按薪级排序)。

    This means that if two elements have the same value or intermediate value (key), they are guaranteed to stay in the same order relative to each other.

    这意味着,如果两个元素具有相同的值或中间值(键),则保证它们彼此之间保持相同的顺序。

    Let's see what I mean with this. Please take a look at this example for a few moments:

    让我们看看我的意思。 请花一点时间看一下此示例:

    >>> d = ["BB", "AA", "CC", "A", "B", "AAA", "BBB"]
    >>> d.sort(key=len)
    >>> d
    ['A', 'B', 'BB', 'AA', 'CC', 'AAA', 'BBB']

    We are comparing the elements based on their length because we passed the len function as the argument for key.

    我们根据元素的长度进行比较,因为我们将len函数作为key的参数进行了传递。

    We can see that there are three elements with length 2: "BB", "AA", and "CC" in that order.

    我们可以看到有三个长度分别为2的元素: "BB""AA""CC"

    Now, notice that these three elements are in the same relative order in the final sorted list:

    现在,请注意,这三个元素在最终排序的列表中的相对顺序相同:

    This is because the algorithm is guaranteed to be stable and the three of them had the same intermediate value (key) during the sorting process (their length was 2, so their key was 2).

    这是因为保证算法稳定,并且在排序过程中它们三个具有相同的中间值(键)(它们的长度为2,所以它们的键为2)。

    💡 Tip: The same happened with "A" and "B" (length 1) and "AAA" and "BBB" (length 3), their original order relative to each other was preserved.

    💡 提示: "A""B" (长度为1)以及"AAA""BBB" (长度为3)也是如此,它们相对的原始顺序得以保留。

    Now you know how the sort() method works, so let's dive into mutation and how it can affect your program.

    现在您知道sort()方法是如何工作的,让我们深入了解突变及其如何影响程序。

    🔹变异与风险 (🔹 Mutation and Risks)

    As promised, let's see how the process of mutation works behind the scenes:

    如所承诺的,让我们看看突变的过程在幕后如何工作:

    When you define a list in Python, like this:

    在Python中定义列表时,如下所示:

    a = [1, 2, 3, 4]

    You create an object at a specific memory location. This location is called the "memory address" of the object, represented by a unique integer called an id.

    您在特定的内存位置创建一个对象。 此位置称为对象的“内存地址”,由称为id的唯一整数表示。

    You can think of an id as a "tag" used to identify a specific place in memory:

    您可以将id视为用于标识内存中特定位置的“标签”:

    You can access a list's id using the id() function, passing the list as argument:

    您可以使用id()函数访问列表的ID,并将列表作为参数传递:

    >>> a = [1, 2, 3, 4]
    >>> id(a)
    60501512

    When you mutate the list, you change it directly in memory. You may ask, why is this so risky?

    当你发生变异的名单,你直接在内存中修改它。 您可能会问,为什么这样有风险?

    It's risky because it affects every single line of code that uses the list after the mutation, so you may be writing code to work with a list that is completely different from the actual list that exists in memory after the mutation.

    这是有风险的,因为它会影响突变后使用列表的每一行代码,因此您可能正在编写代码以使用与突变后内存中存在的实际列表完全不同的列表。

    This is why you need to be very careful with methods that cause mutation.

    这就是为什么您需要非常小心导致变异的方法的原因。

    In particular, the sort() method mutates the list. This is an example of its effect:

    特别地, sort()方法使列表变异 。 这是其效果的一个示例:

    Here is an example:

    这是一个例子:

    # Define a list
    >>> a = [7, 3, 5, 1]
    
    # Check its id
    >>> id(a)
    67091624
    
    # Sort the list using .sort()
    >>> a.sort()
    
    # Check its id (it's the same, so the list is the same object in memory)
    >>> id(a)
    67091624
    
    # Now the list is sorted. It has been mutated!
    >>> a
    [1, 3, 5, 7]

    The list was mutated after calling .sort().

    调用.sort()之后,该列表发生了变化。

    Every single line of code that works with list a after the mutation has occurred will use the new, sorted version of the list. If this was not what you intended, you may not realize that other parts of your program are working with the new version of the list.

    发生突变后,与list a配合使用的每一行代码都将使用列表的新排序版本。 如果这不是您想要的,您可能不会意识到程序的其他部分正在使用列表的新版本。

    Here is another example of the risks of mutation within a function:

    这是一个函数内发生突变的风险的另一个示例:

    # List 
    >>> a = [7, 3, 5, 1]
    
    # Function that prints the elements of the list in ascending order.
    >>> def print_sorted(x):
    	x.sort()
    	for elem in x:
    		print(elem)
    
    # Call the function passing 'a' as argument	
    >>> print_sorted(a)
    1
    3
    5
    7
    
    # Oops! The original list was mutated.
    >>> a
    [1, 3, 5, 7]

    The list a that was passed as argument was mutated, even if that wasn't what you intended when you initially wrote the function.

    即使作为初始编写函数的初衷,作为参数传递的列表a也会发生突变。

    💡 Tip: If a function mutates an argument, it should be clearly stated to avoid introducing bugs into other parts of your program.

    💡 提示:如果函数改变了参数,则应明确声明该参数,以避免将错误引入程序的其他部分。

    🔸sort()方法摘要 (🔸 Summary of the sort() Method)

    • The sort() method lets you sort a list in ascending or descending order.

      sort()方法使您可以按升序或降序对列表进行排序。

    • It takes two keyword-only arguments: key and reverse.

      它使用两个仅关键字的参数: keyreverse

    • reverse determines if the list is sorted in ascending or descending order.

      reverse确定列表是按升序还是降序排序。

    • key is a function that generates an intermediate value for each element, and this value is used to do the comparisons during the sorting process.

      key是一个为每个元素生成中间值的函数,该值用于在排序过程中进行比较。

    • The sort() method mutates the list, causing permanent changes. You need to be very careful and only use it if you do not need the original version of the list.

      sort()方法会使列表发生变化,从而导致永久更改。 您需要非常小心,仅在不需要列表的原始版本时才使用它。

    I really hope that you liked my article and found it helpful. Now you can work with the sort() method in your Python projects. Check out my online courses. Follow me on Twitter. 👍

    我真的希望您喜欢我的文章并认为对您有所帮助。 现在,您可以在Python项目中使用sort()方法。 查看我的在线课程 。 在Twitter上关注我。 👍

    翻译自: https://www.freecodecamp.org/news/the-python-sort-list-array-method-ascending-and-descending-explained-with-examples/

    python升序和降序排序

    展开全文
  • 1)排序基础简单的升序排序是非常容易的。只需要调用sorted()方法。它返回一个新的list,新的list的元素基于小于运算符(__lt__)来排序。>>> sorted([5, 2, 3, 1, 4])[1, 2, 3, 4, 5]你也可以使用list.sor...

    Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列。

    1)排序基础

    简单的升序排序是非常容易的。只需要调用sorted()方法。它返回一个新的list,新的list的元素基于小于运算符(__lt__)来排序。

    >>> sorted([5, 2, 3, 1, 4])

    [1, 2, 3, 4, 5]

    你也可以使用list.sort()方法来排序,此时list本身将被修改。通常此方法不如sorted()方便,但是如果你不需要保留原来的list,此方法将更有效。

    >>> a = [5, 2, 3, 1, 4]

    >>> a.sort()

    >>> a

    [1, 2, 3, 4, 5]

    另一个不同就是list.sort()方法仅被定义在list中,相反地sorted()方法对所有的可迭代序列都有效。

    >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})

    [1, 2, 3, 4, 5]

    2)key参数/函数

    从python2.4开始,list.sort()和sorted()函数增加了key参数来指定一个函数,此函数将在每个元素比较前被调用。 例如通过key指定的函数来忽略字符串的大小写:

    >>> sorted("This is a test string from Andrew".split(), key=str.lower)

    ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

    key参数的值为一个函数,此函数只有一个参数且返回一个值用来进行比较。这个技术是快速的因为key指定的函数将准确地对每个元素调用。

    更广泛的使用情况是用复杂对象的某些值来对复杂对象的序列排序,例如:

    >>> student_tuples = [

    ('john', 'A', 15),

    ('jane', 'B', 12),

    ('dave', 'B', 10),

    ]

    >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age

    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    同样的技术对拥有命名属性的复杂对象也适用,例如:

    >>> class Student:

    def __init__(self, name, grade, age):

    self.name = name

    self.grade = grade

    self.age = age

    def __repr__(self):

    return repr((self.name, self.grade, self.age))

    >>> student_objects = [

    Student('john', 'A', 15),

    Student('jane', 'B', 12),

    Student('dave', 'B', 10),

    ]

    >>> sorted(student_objects, key=lambda student: student.age) # sort by age

    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    3)Operator 模块函数

    上面的key参数的使用非常广泛,因此python提供了一些方便的函数来使得访问方法更加容易和快速。operator模块有itemgetter,attrgetter,从2.6开始还增加了methodcaller方法。使用这些方法,上面的操作将变得更加简洁和快速:

    >>> from operator import itemgetter, attrgetter

    >>> sorted(student_tuples, key=itemgetter(2))

    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    >>> sorted(student_objects, key=attrgetter('age'))

    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    operator模块还允许多级的排序,例如,先以grade,然后再以age来排序:

    >>> sorted(student_tuples, key=itemgetter(1,2))

    [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

    >>> sorted(student_objects, key=attrgetter('grade', 'age'))

    [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

    4)升序和降序

    list.sort()和sorted()都接受一个参数reverse(True or False)来表示升序或降序排序。例如对上面的student降序排序如下:

    >>> sorted(student_tuples, key=itemgetter(2), reverse=True)

    [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

    >>> sorted(student_objects, key=attrgetter('age'), reverse=True)

    [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

    5)排序的稳定性和复杂排序

    从python2.2开始,排序被保证为稳定的。意思是说多个元素如果有相同的key,则排序前后他们的先后顺序不变。

    >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]

    >>> sorted(data, key=itemgetter(0))

    [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]

    注意在排序后'blue'的顺序被保持了,即'blue', 1在'blue', 2的前面。

    更复杂地你可以构建多个步骤来进行更复杂的排序,例如对student数据先以grade降序排列,然后再以age升序排列。

    >>> s = sorted(student_objects, key=attrgetter('age')) # sort on secondary key

    >>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on primary key, descending

    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    以上就是本次介绍的全部实例知识点内容,感谢大家对脚本之家的支持。

    展开全文
  • 学习过python计算机编程语言的同学们都知道,python本身提供了python 列表排序功能,且它的排序算法是稳定的(key相等的两项在排序后的先后次序不变),那么如何如何通过key函数来进行自定义的排序呢?下面的python...

    学习过python计算机编程语言的同学们都知道,python本身提供了python 列表排序功能,且它的排序算法是稳定的(key相等的两项在排序后的先后次序不变),那么如何如何通过key函数来进行自定义的排序呢?

    下面的python源码示例中,我们就要通过python 列表的list.sort来演示一下,如何通过key函数来进行自定义的排序。

    这里说的key函数,其实就是以参加排序的每一项作为输入,而输出则为用来排序的key值。

    #python list 排序

    def my_key1(x):

    return x % 10

    aList = [4, 5, 1, 2, 12, 34, 56, 9 ,80]

    aList.sort() #默认按升序排列

    print(aList)

    aList.sort(reverse = True) #按降序排列

    print(aList)

    #www.iplaypy.com

    aList.sort(key = my_key1) #根据key函数,按照个位数进行升序排列

    print(aList)

    def my_key2(x):

    return x[1]

    aList = [(4,'ab'), (56,'c'), (1,'bb'), (102, 'a')]

    aList.sort(key = my_key2) #按照每个元组的第2分量,即字符串排序

    print(aList)

    玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/code/base/b2512.html

    相关文章 Recommend

    展开全文
  • # 列表排序|去重# 列表的排序:# 升序sort() sorted()a = [1, 3, 5, 2, 6]a.sort()print(a)# =================a = [1, 3, 5, 2, 6]a_sorted = sorted(a)print(a_sorted)# 降序 [::-1] reverse()a = [1, 3, 5]a_list ...
  • # 列表排序|去重# 列表的排序:# 升序sort() sorted()a = [1, 3, 5, 2, 6]a.sort()print(a)# =================a = [1, 3, 5, 2, 6]a_sorted = sorted(a)print(a_sorted)# 降序 [::-1] reverse()a = [1, 3, 5]a_list ...
  • sql升序和降序排列作者|王伟同学任编|郭芮Pandas是用于数据处理和数据分析的非常方便的类库。这也是每个Pythoner进行数据分析的必备工具。但是不可否认的是,并不是所有的程序员都会使用Python,也不是所有的Python...
  • 给定一个字符串, 输出出现次数最多的前三个字符, 若两字符出现次数相同, 则按字典顺序排列.# 样例输入aabbbccde# 样例输出b 3a 2c 2就是先将第二字段降序排序, 再将第一字段升序排序, 关键就是sorted函数key的指定, ...
  • sort是容器的函数:sort(cmp=None, key=None, reverse=False)sorted是python的内建函数:sorted(iterable, cmp=None, key=None, reverse=False)参数解析:cmp:比较函数,比较什么参数由key决定。例如:cmp(e1, e2) ...
  • I am studying for my GCSE part of which requires me to print a dictionary sorted alphabetically by key and the print should include the associated value.I have spent hours trying to find the answer to...
  • python 字典按键值升序排序

    千次阅读 2019-07-23 16:53:44
    # 字典按键值升序排序 def sortDict(data): return dict(sorted(data.items(), key=operator.itemgetter(0), reverse=False))
  • I have a text file(data.txt) containing names and scores 1:1 i.e.:Mike = 1\n John = 2\n Cam = 3\nI want to sort the integers along with the corresponding name in ascending and descending order.with op...
  • python升序排列列表

    万次阅读 2016-11-29 17:37:48
    题目给定list=[2,9,6,45,13],使她升序排列解答 答案一 list = [2,9,6,45,13] list.sort() print list 答案二 list = [2,9,6,45,13] a = sorted(list) print a 思考第一想法是冒泡排序,一个一个进行比较。...
  • 主要介绍了Python实现连接两个无规则列表后删除重复元素并升序排序的方法,涉及Python针对列表的合并、遍历、判断、追加、排序等操作技巧,需要的朋友可以参考下
  • I have a text file(data.txt) containing names and scores 1:1 i.e.:Mike = 1\n John = 2\n Cam = 3\nI want to sort the integers along with the corresponding name in ascending and descending order.with op...
  • I had a huge document that I parsed using regex to give a txt file (json.dump) similar to the following:{"stuff": [{"name": ["frfer","niddsi",],"number": 11300,"identifier": "Tsdsad"},{"name": ["Fast...
  • 本文实例讲述了Python实现连接两个无规则列表后删除重复元素并升序排序的方法。分享给大家供大家参考,具体如下:# -*- coding:utf-8 -*-#! python2list_one=[3,6,2,17,7,33,11,7]list_two=[1,2,3,7,4,2,17,33,11]...
  • 按照频率将数组升序排序.1).题目描述2).解题思路&代码 1).题目描述 给你一个整数数组 nums ,请你将数组按照每个值的频率 升序 排序。如果有多个值的频率相同,请你按照数值本身将它们 降序 排序。 请你返回...
  • 标签:数组、排序 解法 时间复杂度 空间复杂度 执行用时 Ans 1 (Python) O(N)O(N)O(N) O(N)O(N)O(N) 40ms (80%) Ans 2 (Python) Ans 3 (Python) 解法一: class Solution: def frequencySort...
  • 给你一个整数数组 nums ,请你将数组按照每个值的频率 升序 排序。如果有多个值的频率相同,请你按照数值本身将它们 降序 排序。 请你返回排序后的数组。 方法一: 执行用时: 32 ms 内存消耗: 13.5 MB 以字典dict_...
  • python怎么升序和降序排序

    千次阅读 2020-03-18 05:24:53
    python怎么升序和降序排序 1、首先打开cmd命令提示符,输入指令“ipython”打开python的命令行工具: 2、在命令行中...
  • 最近一直在学习算法方面的知识,其实不得...但是建立在不牢靠的基础上的代码是经不起考验的,前面已经写了几篇关于排序算法的博文了,在这里突然想到了一个工具,就是我直接使用python自带的min函数和max函数来进行排序
  • python怎么升序和降序排序

    千次阅读 2020-03-03 16:35:39
    python怎么升序和降序排序 推荐:《python视频教程》 1、首先打开cmd命令提示符,输入指令“ipython”打开python的命令行工具: 2、在命令行中先定义一个变量number数组,里面写入几个数,并用sorted函数对number...
  • Python算法作业】“比较大小并计数,得到升序排列索引位置”的方法进行【升序排序】 # 【1.3.1】“比较大小并计数,得到升序排列索引位置”的方法进行【升序排序】 """ 算法思想:对于待排序的数组中的每一个...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 35,678
精华内容 14,271
关键字:

python升序排序

python 订阅