目录
介绍
内置函数:map; reduce; filter;lambda 表达式
sorted、sort、range、reverse函数
内置函数
map:输入两个参数,第一个是函数,第二个是序列;返回函数fun作用于序列每个元素的组成的列表;
API解释如下:
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of
the argument sequence(s),For example, map(lambda x: x^2, [1, 2, 3, 4, 5]) ->[1, 4, 9, 16, 25]
reduce:输入两个参数,第一个是函数,第二个是序列;返回函数累计逐步作用于序列元素的最终结果;
API解释如下:
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
filter:输入两个参数,第一个是函数,第二个是序列;根据函数作用于序列中每个元素的中间结果(False或者True),决定丢弃或者保留该元素;
filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
顺序遍历
说到顺序遍历,离不开迭代函数,range(list),enumerate(list);前者仅顺序返回元素,后者不仅返回元素且返回元素对应索引;
python的sorted函数和sort均可以对输入序列排序;其区别在于是否保留原始序列;
sorted保留原始序列,且提供关键字key来指定特定的属性字段排序,将排序后的结果保存为新的列表;
## 以下的方法仅python2支持
#itervalues(): 返回字典value值的迭代器,
#iteritems():与items方法相比作用大致相同,只是它的返回值不是列表,而是一个迭代器。
# python3中均在合并在items():以列表方式返回迭代器,无序的状态
# python3 中返回键方法keys(),返回值方法values()
#example1
>> dict1 = {"a":1, "c":4, "b":5}
>>print sorted(dict1) # 默认以key的大小进行升序排序
# 返回key组成的列表 --> # ['a', 'b', 'c']
>>print sorted(dict1, key = lambda x:dict1[x], reverse=True) # 设置以value的大小进行降序排序
# 返回key组成的列表 --> # ['b', 'c', 'a']
>>print sorted(dict1.items()) #默认以key的大小进行排序
#返回(key,value)形式的元组列表
# [('a',1), ('b',5), ('c',4)]
>>print sorted(dict1, key = lambda x:dict1[x]) # 以value的大小进行排序
# 返回key组成的列表 --> # ['a', 'c', 'b']
#example2
>> dict2 = {"a":[1,4], "c":[6,2], "d":[4,3],"b":[5,6]}
>>ret=sorted(dict2.values(),key=lambda x:x[0]) # 以value列表的第1列大小进行升序排序, 返回字典的value对应的列表
# [[1, 4], [4, 3], [5, 6], [6, 2]]
>>ret1 = sorted(dict2.values(),key = lambda x:x[1]) #以value列表的第2列大小进行升序排序, 返回字典的value对应的列表
# [[6, 2], [4, 3], [1, 4], [5, 6]]
>> print sorted(dict2.items(),key = lambda x:x[1][0])#返回以value列表的第1列大小排序的(key-value)元组组成的列表
#[('a', [1, 4]), ('d', [4, 3]), ('b', [5, 6]), ('c', [6, 2])]
## example
In [59]: bb = [[2,1],[3,0],[1,5],[4,2]]
In [60]: t = sorted(bb) #默认以列表第1列元素大小进行排序
Out[60]: [[1, 5], [2, 1], [3, 0], [4, 2]]
In [61]: t = sorted(bb, key=lambda x:x[0]) #以list中每个元素第1列大小进行排序
Out[62]: [[1, 5], [2, 1], [3, 0], [4, 2]]
In [63]: t = sorted(bb, key=lambda x:x[1]) #返回字典的value,且以value第1列大小进行排序
Out[64]: [[3, 0], [2, 1], [4, 2], [1, 5]]
In [65]: cc = [[[2,1],[3,2],[1,5],[4,6]], [[4,10],[2,8],[5,14],[6,2]], [[5,3],[13,4],[7,3],[0,9]]]
In [7]: cc = [[[2,1],[3,2],[1,5],[4,6]], [[4,10],[2,8],[5,14],[6,2]], [[5,3],[13,4],[7,3],[0,9]]]
In [8]: print(np.asarray(cc).shape)
(3, 4, 2)
In [9]: s0 = sorted(cc, key=lambda x:x[0][1]) # 默认每一个元素是一个二维的数组,按
二维数组的第0行第1列的值大小进行排序,即改变最外面一层的二维数组之间的顺序,内部不改变
In [10]: s0
Out[10]:
[[[2, 1], [3, 2], [1, 5], [4, 6]],
[[5, 3], [13, 4], [7, 3], [0, 9]],
[[4, 10], [2, 8], [5, 14], [6, 2]]]
In [11]: s0 = sorted(cc, key=lambda x:x[0][0])
In [12]: s0
Out[12]:
[[[2, 1], [3, 2], [1, 5], [4, 6]],
[[4, 10], [2, 8], [5, 14], [6, 2]],
[[5, 3], [13, 4], [7, 3], [0, 9]]]
In [13]: s1 = sorted(cc, key=lambda x:x[3][0])
In [14]: s1
Out[14]:
[[[5, 3], [13, 4], [7, 3], [0, 9]],
[[2, 1], [3, 2], [1, 5], [4, 6]],
[[4, 10], [2, 8], [5, 14], [6, 2]]]
sort自身排序,覆盖原始序列;如,>>exp_list = [1,6,3,4,2] >> exp_list.sort(reverse=True)>>print(exp_list)
逆向遍历
这里提供几种方式:
>>range(10)[::-1] #可以作为新的对象返回
[9,8,7,6,5,4,3,2,1,0]
>> a=range(10)
>> a.reverse() #reverse方法并不能以新的变量或者对象返回,仅改变原始对象的顺序
>>print(a)
[9,8,7,6,5,4,3,2,1,0]
>>reversed(range(10)) #返回的是一个迭代器对象,并不是具体的变量,需要for循环来遍历加载
<listreverseiterator at 0x37f6241>
实际排序问题
问题描述:txt文件中有两列字段,第一列是str型的人脸图片绝对路径;第二列是对应人脸的质量评分,根据评分,完成对人脸图片的排序,对应关系不变。
思想:借鉴hash思想,进行排序;
# -*- coding: utf-8 -*-
import os
import numpy as np
import time
from collections import OrderedDict
#divide the data into three subsets according to score of each image
def sort_dict(file_name ,dest_dir):
bagan = time.time()
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
#build the dict of (img_path, score) pairs
src_dict = OrderedDict()
with open(file_name,'r') as f:
#len(f.readlines())
for item in f.readlines():
temp_item = item.strip().split()
key = temp_item[0]
value = float(temp_item[1])
src_dict[key] = value
# sort the dict according to score field,that is second column(index=1)
# return new list of tuple dict
list_dict = sorted(src_dict.iteritems(),key=lambda x:x[1],reverse=True)
# write the result into txt files
with open(dest_dir+'score_sorted.txt','w') as f:
for item in list_dict:
f.write(item[0]+' '+str(item[1])+'\n')
print('finish had costed is %d'%(time.time()-bagan))
return list_dict
if __name__=='__main__':
sort_dict(r'1v4w_scores.txt',r'./')