python

 1 def f(x):
 2     return x*x
 3 print map(f,[1,2,3,4,5])
 4 
 5 [1, 4, 9, 16, 25]
 6 
 7 def format_names(s):
 8     return s[0].upper()+s[1:].lower()
 9 print map(format_names,['adam','LISA','barT'])
10 
11 ['Adam', 'Lisa', 'Bart']
12 
13 def prod(x,y):
14     return x*y
15 print reduce(prod,[2,4,5,7,12])
16 
17 3360
18 
19 import math
20 
21 def is_sqr(x):
22     r=int(math.sqrt(x))
23     return r*r==x
24 print filter(is_sqr,range(1,101))
25 
26 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
27 
28 sorted([36,5,12,9,21])
29 Out[7]: [5, 9, 12, 21, 36]
30 
31 def reversed_cmp(x,y):
32     if x>y:
33         return -1
34     if x<y:
35         return 1
36     return 0
37 sorted([36,5,12,9,21],reversed_cmp)
38 
39 Out[8]: [36, 21, 12, 9, 5]
40 
41 
42 def cmp_ignore_case(s1,s2):
43     u1=s1.upper()
44     u2=s2.upper()
45     if u1<u2:
46         return -1
47     if u1>u2:
48         return 1
49     return 0
50 print sorted(['bob','about','Zoo','Credit'],cmp_ignore_case)
51 
52 ['about', 'bob', 'Credit', 'Zoo']
53 
54 def calc_prod(lst):
55     def lazy_prod():
56         def f(x,y):
57             return x*y
58         return reduce(f,lst,1)
59     return lazy_prod
60 f=calc_prod([1,2,3,4])
61 print f()
62 
63 24

 

posted @ 2015-09-03 20:41  小榛子  阅读(124)  评论(0编辑  收藏  举报