我有以下代码:
# 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)它将创建一个4x3的表格,然后按年龄对其进行排序.我的问题是key=operator.itemgetter(1)到底是做什么的? operator.itemgetter函数是否返回项目的值?为什么我不能在那里输入key=a[x][1]之类的内容?可以吗用运算符如何打印诸如3x2的形式的某个值,即22?
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?
Python如何对表进行精确排序?我可以对它进行反向排序吗?
How does exactly Python sort the table? Can I reverse-sort it?
如何根据两列进行排序(例如第一个年龄,然后如果年龄是相同的b名称)?
How can I sort it based on two columns like first age, and then if age is the same b name?
如果没有operator怎么办?
推荐答案
看起来您对所有这些东西有些困惑.
Looks like you're a little bit confused about all that stuff.
operator是一个内置模块,提供了一组便捷的运算符. operator.itemgetter(n)用两个词构造一个可调用对象,该对象假定一个可迭代对象(例如list,tuple,set)作为输入,并从中获取第n个元素.
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.
因此,您不能在那里使用key=a[x][1],因为python不知道x是什么.相反,您可以使用lambda函数(elem只是变量名,没有魔术):
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):
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)因此,这里有个重要的注意事项:在python函数中,一等公民,因此您可以将它们作为参数传递给其他函数.
So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.
其他问题:
有关详细信息,请参阅文档:
Refer to the documentation for details:
更多推荐
operator.itemgetter和sort()在Python中如何工作?
发布评论