-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLambdas
More file actions
72 lines (55 loc) · 2.23 KB
/
Lambdas
File metadata and controls
72 lines (55 loc) · 2.23 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
1. lambda--- for the function never use again --single line function with no name
square= lambda num:num *num #lambda is automatically returned
print(square(7)) #49
add = lambda a,b :a+b
print(add(2,9))
def square2(num) : return num * num
print(square2(8)) #64
print(square2.__name__) # square2
print(square.__name__) #<lambda> ---lambda function don't have name
print(add.__name__) #<lambda>
#example
import tkinter as tk
# DON'T WORRY ABOUT ANY OF THIS CODE
root = tk.Tk()#=====================
frame = tk.Frame(root)#=============
frame.pack()#=======================
# DON'T WORRY ABOUT ANY OF THIS CODE
# Don't need this function if we use a lambda
# def say_hi():
# print("HELLO!")
button = tk.Button(frame,
text="CLICK ME",
fg="red",
command=lambda: print("Hello"))
button2 = tk.Button(frame,
text="CLICK ME",
fg="red",
command=lambda: print("Bye"))
# DON'T WORRY ABOUT ANY OF THIS CODE
button.pack(side=tk.LEFT) #=========
root.mainloop() #===================
# DON'T WORRY ABOUT ANY OF THIS CODE
3.map
# a standard function that accepts at least two arguments: a funtion and a iterable(list, strings, set, dictionary...)
#runs the lambda for each value in the iterable and returns a map object which can be converted into another data structure
nums = [1,2,5,7,9]
doubles = map(lambda x : x *2, nums)
#map can be converted only once--#<map object at 0x104bc9e48>
res = list(doubles)
print(res) #[2, 4, 10, 14, 18]
4.filter
#There is a lambda for each value in the iterable
#returns filter object which can be converted into other iterables
#The object contains only the values that return true to the lambda
lis = [1, 2, 3, 4]
evens = list(filter(lambda x: x-1 ==3, lis)) #第二个参数是要循环的变量集
print(evens) #[4]
names = ["austin", "penny", "angel", "billy"]
a_names = filter(lambda n : n[0] == 'a', names)
print(type(a_names)) #<class 'filter'>
print(list(a_names)) #['austin', 'angel']
print(list(a_names)) #[] --#转化完只有效一次
names2 = ["Lalali", "Colt", "Rusty"]
print(list(map(lambda name : f"Your instructor is {name}", filter(lambda value: len(value) < 5,names2))))
#['Your instructor is Colt']