百行代码入门Python - Chapter 6

以下代码均采用Python 3.5.2编写。新建一个名为HelloWorld.py的文件,当然名字无所谓,输入以下代码:

#filter
def larger100(a):
    return a>100

for i in filter(larger100,[10,56,101,500]):
    print(i)

#reduce
from functools import reduce

data_list = [1,2,5,7,9]
result=reduce(lambda x,y: x+y, data_list)
print(result)

#Generator Expression
def gen():
    for i in range(4):
        yield i

for i in gen():
    print(i)

gen = (x for x in range(4))
for i in gen:
    print(i)

#List Comprehension
l=[]
for i in range(5):
    l.append(i**2)
print(l)

l=[x**2 for x in range(5)]
print(l)

x1=[1,3,5]
y1=[9,12,13]
l=[x**2 for (x,y) in zip(x1,y1) if y>10]
print(l)

#Lazy Evaluation
a=range(10)
result=map(lambda x:x**2, a)
for i in result:
    print(i)

#itertools
from itertools import *
#count(5,2) 5,7,9,11,13,...
#cycle("abc") a b c a b c a b ...
#repeat(1.2) 1.2 1.2 1.2 ...
for i in repeat(10,5):
    print(i)

for i in chain([1,2,3],[4,5,7]):
    print(i)

def height_class(h):
    if h>180:
        return "tall"
    elif h<160:
        return "short"
    else:
        return "middle"

friends = [191, 158, 159, 165, 170, 177, 181, 182, 190]
friends=sorted(friends, key=height_class)
print(friends)
for m,n in groupby(friends, key=height_class):
    print(m)
    print(list(n))

方便起见,可将未读到的代码注释掉,一段段阅读运行,查看结果,理解原理。

上一篇:百行代码入门Python - Chapter 1


下一篇:百行代码入门Python - Chapter 3