operator.itemgetter 和 sort() 在 Python 中是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18595686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does operator.itemgetter and sort() work in Python?
提问by Nickl
I have the following code:
我有以下代码:
# initialize
a = []
# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John", 8, "Student"])
a.append(["Paul", 22, "Car Dealer"])
a.append(["Mark", 66, "Retired"])
# sort the table by age
import operator
a.sort(key=operator.itemgetter(1))
# print the table
print(a)
It creates a 4x3 table and then it sorts it by age. My question is, what exactly key=operator.itemgetter(1)
does? Does the operator.itemgetter
function return the item's value? Why can't I just type something like key=a[x][1]
there? Or can I? How could with operator print a certain value of the form like 3x2
which is 22
?
它创建一个 4x3 表,然后按年龄对其进行排序。我的问题是,究竟是什么key=operator.itemgetter(1)
?该operator.itemgetter
函数是否返回项目的值?为什么我不能在key=a[x][1]
那里输入类似的东西?或者我可以吗?操作员如何打印某个值,例如3x2
which is 22
?
How does exactly Python sort the table? Can I reverse-sort it?
How can I sort it based on two columns like first age, and then if age is the same b name?
How could I do it without
operator
?
Python究竟是如何对表格进行排序的?我可以反向排序吗?
如何根据两列(如第一个年龄)对其进行排序,然后如果年龄与 b 名称相同?
没有我怎么办
operator
?
采纳答案by J0HN
Looks like you're a little bit confused about all that stuff.
看起来你对所有这些东西有点困惑。
operator
is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n)
constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.
operator
是一个内置模块,提供了一组方便的操作符。用两个词operator.itemgetter(n)
构造一个可调用对象,它假定一个可迭代对象(例如列表、元组、集合)作为输入,并从中取出第 n 个元素。
So, you can't use key=a[x][1]
there, because python has no idea what x
is. Instead, you could use a lambda
function (elem
is just a variable name, no magic there):
所以,你不能key=a[x][1]
在那里使用,因为 python 不知道是什么x
。相反,你可以使用一个lambda
函数(elem
只是一个变量名,没有魔法):
a.sort(key=lambda elem: elem[1])
Or just an ordinary function:
或者只是一个普通的函数:
def get_second_elem(iterable):
return iterable[1]
a.sort(key=get_second_elem)
So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.
所以,这里有一个重要的注意事项:在 python 中,函数是一等公民,因此您可以将它们作为参数传递给其他函数。
Other questions:
其他问题:
- Yes, you can reverse sort, just add
reverse=True
:a.sort(key=..., reverse=True)
- To sort by more than one column you can use
itemgetter
with multiple indices:operator.itemgetter(1,2)
, or with lambda:lambda elem: (elem[1], elem[2])
. This way, iterables are constructed on the fly for each item in list, which are than compared against each other in lexicographic(?) order (first elements compared, if equal - second elements compared, etc) - You can fetch value at [3,2] using
a[2,1]
(indices are zero-based). Using operator... It's possible, but not as clean as just indexing.
- 是的,您可以反向排序,只需添加
reverse=True
:a.sort(key=..., reverse=True)
- 要按多列排序,您可以使用
itemgetter
多个索引:operator.itemgetter(1,2)
或 lambda:lambda elem: (elem[1], elem[2])
。这样,可以为列表中的每个项目动态构建可迭代对象,然后按字典(?)顺序相互比较(比较第一个元素,如果相等 - 比较第二个元素等) - 您可以使用 [3,2] 获取值
a[2,1]
(索引从零开始)。使用运算符...这是可能的,但不像索引那样干净。
Refer to the documentation for details:
有关详细信息,请参阅文档:
回答by Paulo Almeida
You are asking a lot of questions that you could answer yourself by reading the documentation, so I'll give you a general advice: read it and experiment in the python shell. You'll see that itemgetter
returns a callable:
你问了很多问题,你可以通过阅读文档来回答自己,所以我会给你一个一般性的建议:阅读它并在 python shell 中进行实验。你会看到itemgetter
返回一个可调用的:
>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8
To do it in a different way, you can use lambda
:
要以不同的方式做到这一点,您可以使用lambda
:
a.sort(key=lambda x: x[1])
And reverse it:
并反转它:
a.sort(key=operator.itemgetter(1), reverse=True)
Sort by more than one column:
按多列排序:
a.sort(key=operator.itemgetter(1,2))
See the sorting How To.
请参阅排序方法。
回答by Lutz Prechelt
Answer for Python beginners
Python初学者的答案
In simpler words:
简单来说:
- The
key=
parameter ofsort
requires a key function(to be applied to be objects to be sorted) rather than a single key valueand - that is just what
operator.itemgetter(1)
will give you: A functionthat grabs the first item from a list-like object.
- 所述
key=
的参数sort
需要密钥函数(要施加到要进行排序的对象),而不是单个密钥值和 - 这正是
operator.itemgetter(1)
会给你:一个功能是从列表状物体抓住的第一个项目。
(More precisely those are callables, not functions, but that is a difference that can often be ignored.)
(更准确地说,那些是callables,而不是函数,但这是一个经常可以忽略的差异。)
回答by user2329366
#sorting first by age then profession,you can change it in function "fun".
a = []
def fun(v):
return (v[1],v[2])
# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John", 8, "Student"])
a.append(["Paul", 8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])
a.sort(key=fun)
print a
回答by shubham sinha
a = []
a.append(["Nick", 30, "Doctor"])
a.append(["John", 8, "Student"])
a.append(["Paul", 8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])
print a
[['Nick', 30, 'Doctor'], ['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Mark', 66, 'Retired']]
def _cmp(a,b):
if a[1]<b[1]:
return -1
elif a[1]>b[1]:
return 1
else:
return 0
sorted(a,cmp=_cmp)
[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]
def _key(list_ele):
return list_ele[1]
sorted(a,key=_key)
[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]
>>>