相关疑难解决方法(0)

operator.itemgetter和sort()如何在Python中工作?

我有以下代码:

# 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]?或者我可以吗?与运营商怎么能打印等形式的一定值3x222

  1. Python如何对表进行排序?我可以反向排序吗?

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

  3. 我怎么能不这样做operator

python sorting operator-keyword

53
推荐指数
3
解决办法
12万
查看次数

我如何"压缩排序"并行numpy数组?

如果我有两个并行列表,并希望按照第一个元素的顺序对它们进行排序,那么很容易:

>>> a = [2, 3, 1]
>>> b = [4, 6, 7]
>>> a, b = zip(*sorted(zip(a,b)))
>>> print a
(1, 2, 3)
>>> print b
(7, 4, 6)
Run Code Online (Sandbox Code Playgroud)

如何使用numpy数组而不将它们解压缩到传统的Python列表中呢?

python sorting numpy

47
推荐指数
2
解决办法
2万
查看次数

标签 统计

python ×2

sorting ×2

numpy ×1

operator-keyword ×1