Python高次関数-map/reduce/filter/sorted

2603 ワード

# ##     
from functools import reduce

print(abs(-10))
print(abs)  #   
#            
f = abs
print(f)
print(f(-19))


# #    
#               
def add(x, y, f):
    return f(x) + f(y)


print(
    add(-6, -7, abs)
)


#       ,                

# #map()        ,     ,    Iterable(     )
# map()         Iterable    
def f(x):
    return x * x


r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(
    list(r)
)

#             
print(
    list(map(str, [1, 2, 3, 4, 5, 6, 7, 8]))
)


# #reduce()        ,     ,      
# reduce()                     
#     reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

#         
def add(x, y):
    return x + y


print(
    reduce(add, [1, 2, 3, 4, 5, 6, 7, 8, 9])
)

#     str2int  
d = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}


def str2int(s):
    def fn(x, y):
        return 10 * x + y

    def char2int(s):
        return d[s]

    return reduce(fn, map(char2int, s))


print(
    str2int('95949748')
)


#          
def normalize(name_list):
    def fn(name):
        if not isinstance(name, str):
            raise TypeError('Wrong type!')
        return str(name[0]).upper() + str(name[1:]).lower()

    return map(fn, name_list)


L1 = ['adam', 'LISA', 'barT']
print(
    list(normalize(L1))
)


#          
def product(number_list):
    return reduce(lambda x, y: x * y, number_list)


print(
    product([1, 2, 3, 4, 5, 6])
)


# #filter()  
# filter()            。 map()    ,
# filter()               ,        True  False           。

#                 

def is_odd(n):
    return n % 2 == 1


print(
    list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))
)


#              
def is_empty(s_list):
    return s_list and s_list.strip()


print(
    list(filter(is_empty, ['A', 'C', 'E', 'G', None, 'J', ' ']))
)

# # sort()       
a = [-30, -4, -5, 9, 6, 7]
s = ['Z', 'a', 'c', 'F']
print(
    sorted(a, key=abs)  #       
)
print(
    sorted(a)  #        
)
print(
    sorted(a, reverse=True)  #       
)

print(
    sorted(s)  #  ASCII      ,'Z' < 'a',    Z       a   。
)
print(
    sorted(s, key=str.lower)  #            。
)

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
#       
print(
    sorted(L, key=lambda x: x[0])
)
#         
print(
    sorted(L, key=lambda x: x[1])
)