Nic*_*ckl 53 python sorting operator-keyword
我有以下代码:
# 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)
Run Code Online (Sandbox Code Playgroud)
它创建一个4x3表,然后按年龄对其进行排序.我的问题是,到底是key=operator.itemgetter(1)做什么的?该operator.itemgetter函数是否返回项目的值?为什么我不能只输入那样的东西key=a[x][1]?或者我可以吗?与运营商怎么能打印等形式的一定值3x2是22?
Python如何对表进行排序?我可以反向排序吗?
如何根据第一个年龄段的两列对其进行排序,然后如果年龄与b名称相同?
我怎么能不这样做operator?
J0H*_*0HN 92
看起来你对这些东西有点困惑.
operator是一个内置模块,提供一组方便的操作员.用两个词operator.itemgetter(n)构造一个可调用的函数,它将一个可迭代的对象(例如list,tuple,set)作为输入,并从中取出第n个元素.
所以,你不能key=a[x][1]在那里使用,因为python不知道是什么x.相反,你可以使用一个lambda函数(elem只是一个变量名,没有魔法):
a.sort(key=lambda elem: elem[1])
Run Code Online (Sandbox Code Playgroud)
或者只是一个普通的功能:
def get_second_elem(iterable):
return iterable[1]
a.sort(key=get_second_elem)
Run Code Online (Sandbox Code Playgroud)
所以,这里有一个重要的注意事项:在python函数中是一等公民,所以你可以将它们作为参数传递给其他函数.
其他问题:
reverse=True: a.sort(key=..., reverse=True)itemgetter多个索引:operator.itemgetter(1,2)或使用lambda : lambda elem: (elem[1], elem[2]). 通过这种方式,可以为列表中的每个项目动态构建迭代,然后以字典(?)顺序相互比较(比较第一个元素,如果相等,则比较第二个元素等)a[2,1](索引从零开始)在[3,2]处获取值.使用运算符......这是可能的,但不像索引一样干净. 有关详细信息,请参阅文档:
Lut*_*elt 25
用简单的话说:
key=的参数sort需要密钥函数(要施加到要进行排序的对象),而不是单个密钥值和operator.itemgetter(1)会给你:一个功能是从列表状物体抓住的第一个项目.(更准确地说,这些是可调用的,而不是功能,但这是一个经常可以忽略的差异.)
Pau*_*ida 11
你正在通过阅读文档问自己可以回答的很多问题,所以我会给你一个一般的建议:阅读它并在python shell中进行实验.你会看到itemgetter返回一个可调用的:
>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8
Run Code Online (Sandbox Code Playgroud)
要以不同的方式执行此操作,您可以使用lambda:
a.sort(key=lambda x: x[1])
Run Code Online (Sandbox Code Playgroud)
并扭转它:
a.sort(key=operator.itemgetter(1), reverse=True)
Run Code Online (Sandbox Code Playgroud)
按多列排序:
a.sort(key=operator.itemgetter(1,2))
Run Code Online (Sandbox Code Playgroud)
请参阅排序方法.
| 归档时间: |
|
| 查看次数: |
122182 次 |
| 最近记录: |