Python中高次関数---sorted,filter,map

3101 ワード

sorted
sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.

パラメータreverse
a = [1,2,3,4,5]
a1 = sorted(a,reverse=True)
print('    a1:{},a:{}'.format(a1,a))


  :
    a1:[5, 4, 3, 2, 1],a:[1, 2, 3, 4, 5]

パラメータkey
keyは関数を受け入れることができます.
l = [2,-3,5,-1,-8,2]
print('l:',l)
print('sorted(l):',sorted(l)) #      
print('sorted(l,key=abs):',sorted(l,key=abs)) #abs     ,   

l1 = [[1,3,'a'],['e'],'dsfeee',[5,9]]
def func(l):
    return len(l)
print('sorted(l1,key=func):',sorted(l1,key=func)) #        


  :
l: [2, -3, 5, -1, -8, 2]
sorted(l): [-8, -3, -1, 2, 2, 5]
sorted(l,key=abs): [-1, 2, 2, -3, 5, -8]
sorted(l1,key=func): [['e'], [5, 9], [1, 3, 'a'], 'dsfeee']

keyによるソート:
from operator import itemgetter,attrgetter

d = {'bob':13,'nacy':3,'kity':44,'sunny':31}
d1 = sorted(d,key=itemgetter(0))  # key  ,  value  
d2 = sorted(d,key=itemgetter(1))  # value  ,  key  
print('d1:',d1)
print('d2:',d2)
d3 = sorted(d.items(),key=itemgetter(1))# value  ,        
print('d3:',d3)

D = [('a',4,2),('b',1,4),('c',2,6),('d',1,1)]
D1 = sorted(D,key=itemgetter(1))
D2 = sorted(D,key=itemgetter(1,2)) #    
print('D1',D1)
print('D2(    )',D2)



  :
d1: ['bob', 'kity', 'nacy', 'sunny']
d2: ['nacy', 'kity', 'bob', 'sunny']
d3: [('nacy', 3), ('bob', 13), ('sunny', 31), ('kity', 44)]
D1 [('b', 1, 4), ('d', 1, 1), ('c', 2, 6), ('a', 4, 2)]
D2(    ) [('d', 1, 1), ('b', 1, 4), ('c', 2, 6), ('a', 4, 2)]

filter
Init signature: filter(self, /, *args, **kwargs)
Docstring:     
filter(function or None, iterable) --> filter object
filter関数の戻り値はfilterオブジェクトであり、listメソッドを使用してfilter関数の戻り値をリストに変換します.
def clear_data(e):
    if isinstance(e,int) or isinstance(e,float):
        return True
    else:
        return False
    
l = ['e',5,8.9,[3,4],22,True,('a',3),0]
f = list(filter(clear_data,l))
print('filter:',f)
print('True ==1:',True ==1)



  :
filter: [5, 8.9, 22, True, 0]
True ==1: True

map
Init signature: map(self, /, *args, **kwargs)
Docstring:     
map(func, *iterables) --> map object
map関数の戻り値もmapオブジェクトであり、mapクラスのインスタンスであり、listメソッドを使用してリストに変換されます.
def m(e):
    return e**2+1
l = [1,2,3,4]
r = list(map(m,l))
print('list(map(m,l)):',r)



  :
list(map(m,l)): [2, 5, 10, 17]