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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:11:42  来源:igfitidea点击:

How does operator.itemgetter and sort() work in Python?

pythonsortingoperator-keyword

提问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.itemgetterfunction 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 3x2which is 22?

它创建一个 4x3 表,然后按年龄对其进行排序。我的问题是,究竟是什么key=operator.itemgetter(1)?该operator.itemgetter函数是否返回项目的值?为什么我不能在key=a[x][1]那里输入类似的东西?或者我可以吗?操作员如何打印某个值,例如3x2which is 22

  1. How does exactly Python sort the table? Can I reverse-sort it?

  2. How can I sort it based on two columns like first age, and then if age is the same b name?

  3. How could I do it without operator?

  1. Python究竟是如何对表格进行排序的?我可以反向排序吗?

  2. 如何根据两列(如第一个年龄)对其进行排序,然后如果年龄与 b 名称相同?

  3. 没有我怎么办operator

采纳答案by J0HN

Looks like you're a little bit confused about all that stuff.

看起来你对所有这些东西有点困惑。

operatoris 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 xis. Instead, you could use a lambdafunction (elemis 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:

其他问题:

  1. Yes, you can reverse sort, just add reverse=True: a.sort(key=..., reverse=True)
  2. To sort by more than one column you can use itemgetterwith 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)
  3. 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.
  1. 是的,您可以反向排序,只需添加reverse=Truea.sort(key=..., reverse=True)
  2. 要按多列排序,您可以使用itemgetter多个索引:operator.itemgetter(1,2)或 lambda: lambda elem: (elem[1], elem[2])。这样,可以为列表中的每个项目动态构建可迭代对象,然后按字典(?)顺序相互比较(比较第一个元素,如果相等 - 比较第二个元素等)
  3. 您可以使用 [3,2] 获取值a[2,1](索引从零开始)。使用运算符...这是可能的,但不像索引那样干净。

Refer to the documentation for details:

有关详细信息,请参阅文档:

  1. operator.itemgetterexplained
  2. Sorting list by custom key in Python
  1. operator.itemgetter解释
  2. 在 Python 中按自定义键对列表进行排序

回答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 itemgetterreturns 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:

简单来说:

  1. The key=parameter of sortrequires a key function(to be applied to be objects to be sorted) rather than a single key valueand
  2. that is just what operator.itemgetter(1)will give you: A functionthat grabs the first item from a list-like object.
  1. 所述key=的参数sort需要密钥函数(要施加到要进行排序的对象),而不是单个密钥
  2. 这正是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']]
>>>