0.应用背景
在编程中,A、B两个数组存在一定对应关系;若其中一个数组需要进行排序,另外一个数组也需要根据相同顺序进行调整。
1.使用sorted()函数排序
想将数组A、B使用zip()函数进行压缩,sorted()排序之后,利用zip(*zipped)进行解压缩。
A = [1,2,3,4,5,6]
B = ['h','e','l','l','o',',']
Z = zip(A,B)
Z = sorted(Z,reverse=True)
print(Z)
#result:[(6, ','), (5, 'o'), (4, 'l'), (3, 'l'), (2, 'e'), (1, 'h')]
A_new,B_new = zip(*Z)
print(A_new,'\n',B_new)
# result:
# (6, 5, 4, 3, 2, 1)
# (',', 'o', 'l', 'l', 'e', 'h')
2.sorted函数用法简介(http://www.runoob.com/python/python-func-sorted.html)
sorted(iterable, cmp=None, key=None, reverse=False)
参数详解:
- iterable:是可迭代类型;
- cmp:用于比较的函数,比较什么由key决定;
- key:用列表元素的某个属性或函数进行作为关键字,有默认值,迭代集合中的一项;
- reverse:排序规则. reverse = True 降序 或者 reverse = False 升序,有默认值。
- 返回值:是一个经过排序的可迭代类型,与iterable一样。
3.zip() 函数简介(http://www.runoob.com/python/python-func-zip.html)
zip([iterable, ...])
参数说明:
- iterabl -- 一个或多个迭代器;
- 返回值:返回元组列表。
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]