>>> def f(x): ... return x * x ... L = [] for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: L.append(f(n)) print(L)
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> list(r) [1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) ['1', '2', '3', '4', '5', '6', '7', '8', '9']
def normalize(name): return name.capitalize() l1=["adam","LISA","barT"] l2=list(map(normalize,l1)) print(l2)
>>> from functools import reduce >>> def fn(x, y): ... return x * 10 + y ... >>> reduce(fn, [1, 2, 3, 4, 5]) 12345
from functools import reduce def pro (x,y): return x * y def prod(L): return reduce(pro,L) print(prod([1,3,5,7]))
CHAR_TO_FLOAT = { '0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9, '.': -1 } def str2float(s): nums = map(lambda ch:CHAR_TO_FLOAT[ch],s) point = 0 def to_float(f,n): nonlocal point if n==-1: point =1 return f if point ==0: return f*10+n else: point =point *10 return f + n/point return reduce(to_float,nums,0)#第三个参数0是初始值,对应to_float中f
def is_odd(n): return n % 2 == 1 list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # 结果: [1, 5, 9, 15]
def _odd_iter(): n = 1 while True: n = n + 2 yield n #这是一个生成器,并且是一个无线序列
def _not_pisible(n): return lambda x: x % n > 0
def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_pisible(n), it) # 构造新序列
for n in primes(): if n < 100: print(n) else: break
>>> sorted([36, 5, -12, 9, -21]) [-21, -12, 5, 9, 36]
>>> sorted([36, 5, -12, 9, -21], key=abs) [5, 9, -12, -21, 36]
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower) ['about', 'bob', 'Credit', 'Zoo']
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) ['Zoo', 'Credit', 'bob', 'about']
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def by_score(t): for i in t: return t[1] L2=sorted(L,key= by_score) print(L2)
L2=sorted(L,key=lambda t:t[1]) print(L2)
以上就是Python常见的内建函数介绍的详细内容,更多请关注Gxl网其它相关文章!
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did84496