map , filter , reduce ,zip

簡單使用map , filter , reduce ,zip請參照: https://www.bilibili.com/read/cv1517879

如需進階 lambda 請參考此鏈接第一條7篇  https://www.zhihu.com/question/21936396/answer/121880616

寫代碼之前請一定考慮好 輸入輸出 類型和語義

 

此博客記錄一些組合操作: 

# 挑選所有有數字特徵的名字   dict [(str,obj)] ->  dict [(str,obj)] -> [str]

sample = r[0][0][0] 
temp = filter(lambda x:not isinstance(x[1],str) and  not isinstance(x[1],dict) and  not isinstance(x[1],tuple),sample.items())
keys = list(map(lambda x:x[0],temp) )

 # 挑選特徵符合之前的名字  (dict,dict)  ->  (dict,dict) 

# dict -> dict
def choose_items(d):
    return dict(filter(lambda x: x[0] in keys, d.items()))
# (dict,dict)->(dict,dict)
def choose_items_tuple(x):
    return (choose_items(x[0]),choose_items(x[1]))
# [(dict,dict)]->[(dict,dict)]
def choose_items_s(x):
    return map(choose_items_tuple,x)
# [[(dict,dict)]]->[[(dict,dict)]]
def choose(x):
    return map(choose_items_s,x)

feature = choose(r)

# [[(dict,dict)]] -> [[dict]]

## (dict,dict)-> dict
### ([(str,float)],[(str,float)])-> [((str,float),(str,float))]
def a(x):
    return zip(x[0].items(),x[1].items())
### [((str,float),(str,float))] -> [(str,float)]
#### ((str,float),(str,float)) -> (str,float)
def b(x):
    return (x[0][0],x[0][1]-x[1][1])
#### map
def c(x):
    return map(b,x)

## [(dict,dict)]-> [dict]
def d(x):
    return map(lambda y:c(a(y)),x)

## [[(dict,dict)]]-> [[dict]]
def e(x):
    return map(d,x)

# 平均  # [[[(str, float)]]] ->  [[(str, float)]]

## [[(str, float)]] -> [(str, float)]


##1 [[(str, float)]] -> [(str, [float])]

###1  [[(str, float)]] -> [[(str, [float])]]
#### [(str, float)] -> [(str, [float])]
##### (str, float) -> (str, [float])
def p(x):
    return (x[0],[x[1]])   
##### map
def p2(x):
    return map(p,x)
#### map
def p3(x):
    return map(p2,x)

###2   [[(str, [float])]] -> [(str, [float])]
#### [(str, [float])] -> [(str, [float])] -> [(str, [float])]
#####1 zip [(str, [float])] -> [(str, [float])] -> [((str, [float]), (str, [float]))]
def p4(x,y):
    return zip(x,y)
#####2 [((str, [float]), (str, [float]))] -> [(str, [float])]
###### ((str, [float]), (str, [float])) ->  (str, [float])  鏈表鏈接
def p5(x):
    return (x[0][0],x[0][1]+x[1][1])
###### map
def p6(x):
    return map(p5,x)
##### pipe 
def p7(x,y):
    return p6(p4(x,y))
#### reduce
def p8(x):
    return reduce(p7,x)
### pipe
def p9(x):
    return p8(p3(x))


##2 [(str, [float])] -> [(str, float)]
### (str, [float]) -> (str, float)
def p10(x):
    temp = list(x[1])
    mean = float(sum(temp))/float(len(temp))
    return (x[0], mean)
### map
def p11(x):
    return map(p10,x)
## pipe
def p12(x):
    return p11(p9(x))
## map
def p13(x):
    return map(p12,x)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章