廖雪峰Python+Git+javascript教程离线

file:///F:/【2】Python 、机器学习/廖雪峰Python+Git+javascript教程离线版/wiki/python27/0013868200385680e8cf932dba9433ea367de9aba2b4784000.htm

## 迭代
for value1,value2 in ([[1,3],[111,33],[22222,36235]]):
    print value1,value2

##################################
##列表生成式
print range(1,5)

print [x*2 for x in range(1,5)]

print [x*y for x in range(1,5) for y in range(1,5)]

print [x*x for x in range(1,13) if x%2 ==0]


import os
print [x for x in os.listdir('.')]


##L = ['Hello', 'World', 18, 'Apple', None]
##print [s.lower for s in L if isinstance(s,str)]

##################################
##生成器    使用圆括号
print '生成器'

g = (x * x for x in range(10))
print g
##print g.next()
##print g.next()
##print g.next()
##print g.next()
##print g.next()

for n in g:
    print n

print '用生成器生成斐波那契数列'
def fib(max):
    n,a,b =0,0,1
    while n<max:
        yield b
        a,b = b,a+b
        n= n+1
for n in fib(8):
    print n

##函数################################
print '函数'
def add(x,y,f):
    return f(x)+f(y)
print add(4,-9,abs)

import math
print math.pi

##   map   reduce################################
print 'map   reduce'
print map(abs,[11,22,33,-222,2223,-655])

def str2int(s):
    def fn(x,y):
        return x*10+y
    def char2num(s):
        return {'0':0,'1':1,'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    return reduce(fn,map(char2num,s))

print 'string to int',str2int('123564253')

##Python内建的filter()函数用于过滤序列################################
print 'filter'
def is_odd(n):
    return n % 2 == 1

print filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])

## sorted 函数################################
print 'sorted'
def reversed_cmp(x, y):
    if x > y:
        return -1
    if x < y:
        return 1
    return 0

print sorted([36, 5, 12, 9, 21], reversed_cmp)

def cmp_ignore_case(s1, s2):
    u1 = s1.upper()
    u2 = s2.upper()
    if u1 < u2:
        return -1
    if u1 > u2:
        return 1
    return 0

print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)

  

posted @ 2017-02-20 22:38  tmjDD  阅读(524)  评论(0编辑  收藏  举报