python list 比较大小问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python list 比较大小问题相关的知识,希望对你有一定的参考价值。
有个a=[[a1, b1, c1], [a2, b2, c2], [a3, b3, c3], [a4, b4, c4]]
要按c1, c2, c3, c4的值重新排a中四个元素的位置
应该怎么做啊?
谢谢大虾们~~~
下面是联机文档的内容:
The sort() and reverse() methods modify the list in place for economy of
space when sorting or reversing a large list. To remind you that they operate by
side effect, they don’t return the sorted or reversed list.
The sort() method takes optional arguments for controlling the
comparisons.cmp specifies a custom comparison function of two arguments (list
items) which should return a negative, zero or positive number depending on
whether the first argument is considered smaller than, equal to, or larger than
the second argument: cmp=lambdax,y:cmp(x.lower(),y.lower()). The
default value is None.key specifies a function of one argument that is used to extract a
comparison key from each list element: key=str.lower. The default value is None.reverse is a boolean value. If set to True, then the list
elements are sorted as if each comparison were reversed.In general, the key and reverse conversion processes are
much faster than specifying an equivalent cmp function. This is because
cmp is called multiple times for each list element while key
and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style
cmp function to a key function.Changed in version 2.3:
Support for None as an equivalent to omitting cmp was
added.Changed in version 2.4:
Support for key and reverse was added.
Starting with Python 2.3, the sort() method is
guaranteed to be stable. 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).
CPython implementation detail: While a list is being sorted,
the effect of attempting to mutate, or even inspect, the list is undefined. The
C implementation of Python 2.3 and newer makes the list appear empty for the
duration, and raises ValueError if it
can detect that the list has been mutated during a sort. 参考技术A a.sort(key = lambda x:x[-1])
Python---sorted
# sorted # 排序算法 # 排序也是在程序中经常用到的算法 # 无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小 # 如果是数字,我们可以直接比较,但是如果是字符串或者两个dict,直接比较数学上的大小是没有意义的,因此,比较的过程必须通过函数抽象出来 # Python内置的sorted()函数就可以对list进行排序 l = sorted([36, 5, -12, 9, -21]) print(l) # 此外,sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序 # 按绝对值大小排序 l = sorted([36, 5, -12, 9, -21], key=abs) print(l) # key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序 # 字符串排序 l = sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘]) print(l) # 默认情况下,对字符串排序,是按照ASCII的大小比较的,由于‘Z‘ < ‘a‘,结果大写字母Z会排在小写字母a的前面 # 字符串忽略大小写,按字母排序 l = sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], key=str.lower) print(l) # 反向排序 l = sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], key=str.lower, reverse=True) print(l) # 高阶函数的抽象能力强大,核心代码可以保持简洁
以上是关于python list 比较大小问题的主要内容,如果未能解决你的问题,请参考以下文章