-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07_lambda_test.py
25 lines (19 loc) · 983 Bytes
/
07_lambda_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Demonstration of various ways to use lambda functions.
from functools import reduce
def signal(x): return 'Buy' if x <= 25 else 'Sell' if x >= 75 else 'No change'
data = [50, 10, 90]
action = list(map(signal, data))
print('function result:', action)
# The lambda function used here is the equivalent of the function above
action = list(map(lambda x: 'Buy' if x <= 25 else 'Sell' if x >= 75 else 'No change', data))
# map functions can alternatively be written as list comprehensions like this:
# action = [signal(x) for x in data]
print('lambda result:', action)
action = list(filter(lambda x: x == 'Buy' or x == 'Sell', action))
# filter functions can alternatively be written as list comprehensions:
# action = [x for x in action if x == 'Buy' or x == 'Sell']
print(action)
# Demonstrates reduce function, which applies a function to the first value,
# retains the result, and repeats for the next value in a list.
trend = reduce(lambda x, y: (x + y)/2, data)
print(trend)