Python3 zip,lambda,map,reduce的使用

时间:2022-08-17 18:25:26

使用Python进行数据处理的时候经常遇到一些Python独有的小函数,使用这些小函数
可以大大减少代码量。Python2中的使用方法与3有些不同,具体参见
这里写链接内容

# -*- coding: utf-8 -*-
""" Created on Wed Oct 26 11:51:32 2016 @author: Jian """
import functools
a = [1,2,3,4,5]
b = [2,2,9,0,9]

def pick_the_largest(a, b):
    result = []  # A list of the largest values

    # Assume both lists are the same length
    list_length = len(a)
    for i in range(list_length):
        result.append(max(a[i], b[i]))
    return result

print(pick_the_largest(a, b))


""" This function takes two equal-length collections, and merges them together in pairs. If we use this on our list of values, we get the following: [2, 2, 9, 4, 9] """
print(list(zip(a,b)))
""" function 参数:返回值 """

f = lambda x, y : x + y
print(f(1,1))
""" map(func,seq) func是计算的函数,seq是传入的数组 """
def fahrenheit(T):
     return ((float(9)/5)*T + 32)

def celsius(T):
     return (float(5)/9)*(T-32)
temperatures = (36.5, 37, 37.5, 38, 39)
F = map(fahrenheit, temperatures)
C = map(celsius, F)

temperatures_in_Fahrenheit = list(map(fahrenheit, temperatures))
temperatures_in_Celsius = list(map(celsius, temperatures_in_Fahrenheit))
print(temperatures_in_Fahrenheit)
print(temperatures_in_Celsius)
""" map lambda 配合使用效果更好 """
C = [39.2, 36.5, 37.3, 38, 37.8] 
F = list(map(lambda x: (float(9)/5)*x + 32, C))
print(F)

""" lambda 写计算函数,a,b传入两个数组参数 [18, 14, 14, 14] """
a = [1,2,3,4]
b = [17,12,11,10]
c = [-1,-4,5,9]
print(list(map(lambda x,y:x+y, a,b)))
""" filter(function, sequence) 返回True的数进数组 """

fibonacci = [0,1,1,2,3,5,8,13,21,34,55]
odd_numbers = list(filter(lambda x: x % 2, fibonacci))
print(odd_numbers)
""" 113 102 """
print(functools.reduce(lambda x,y: x+y, [47,11,42,13]))
#累加
from functools import reduce
#找到最大值
f = lambda a,b: a if (a > b) else b
print(reduce(f, [47,11,42,102,13]))
#累乘
print(reduce(lambda x, y: x*y, range(1,3)))
m = list(range(1,3))
#[1, 2]
print(m)