Python特性: 切片通过冒号’:’来截取: 如list,tuple,string,实例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#定义一个list:显示1到100,如L:[1,2,3,4,...100],切片实例
L = range(21)
>>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> L[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L[1:21]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> L[1:21:2]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> L[::]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> L[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> L[-10:]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
#但是顺序不能倒过来
>>> L[10:9]
[]
迭代判断是否可迭代可以使用for …in …的方式来进行迭代,但是需要判断in后面的数据类型是否可迭代:
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False
对dict进行迭代:对key:
>>> grades = {'Daniel':22,'Sandy':42,'Andy':33}
>>> for key in grades:
... print grades[key]
...
22
33
42
对value:
>>> for value in grades.itervalues():
... print value
...
22
33
42
对list进行“索引-值”格式的迭代Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:
>>> L = ['apple','pear','peach','banaba']
>>> L
['apple', 'pear', 'peach', 'banaba']
>>> for x,y in enumerate(L):
... print x,y
...
0 apple
1 pear
2 peach
3 banaba
列表生成式利用range()函数: 但如果要生成[1x1,2x2, 3x3, ..., 10x10]怎么做? 法一,是循环:
>>> L = []
>>> for x in range(1,11):
... L.append(x*x)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
法二,利用生成器,可以这么做:
>>> [x*x for x in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
如果循环里有条件判断,如要筛选出仅偶数的平方:
>>> [x*x for x in range(1,11) if x%2 == 0]
[4, 16, 36, 64, 100]
可以实现两层循环:
>>> [a+b for a in 'ABC' for b in 'abc']
['Aa', 'Ab', 'Ac', 'Ba', 'Bb', 'Bc', 'Ca', 'Cb', 'Cc']
>>> import os
>>> [d for d in os.listdir('.')]
['AppData', 'Application Data', 'Contacts', 'Cookies', 'Desktop', 'Documents', 'Videos']
>>> for x,y in d.iteritems():
... print '\'',x,'\':',y
..
' a ': 1
' c ': 3
' b ': 2
>>> ['\''+x+'\':'+str(y) for x,y in d.iteritems()]
["'a':1", "'c':3", "'b':2"]
生成器Python中一边循环一边计算的机制就是生成器,可以这样使用:
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x03F963A0>
>>> g.next()
0
>>> g.next()
1
>>> g.next()
4
这样有点烦,可以循环遍历:
>>> g = (x*x for x in range(10))
>>> for n in g:
print n
0
1
4
9
16
25
36
49
64
81
所以,我们创建了一个generator后,基本上永远不会调用next()方法,而是通过for循环来迭代它。 generator非常强大。如果推算的算法比较复杂,用类似列表生成式的for循环无法实现的时候,还可以用函数来实现。 比如,著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到: 1, 1, 2, 3,5, 8, 13, 21, 34, ... 首先需要理解:
>>> a,b = 1,2
>>> a,b = b,a+b #同时处理a=b,b=a+b,没有先后顺序
>>> a
2
>>> b
3
那么配波纳契数列可以这么写:
>>> def fib(max):
n, a, b = 0, 0, 1
while n < max:
print b #generator函数:yield b
a, b = b, a + b
n = n + 1
>>>
>>> fib(4)
1
1
2
3
上面的函数改为generator,只需要把printb改为yieldb就可以了.
>>> def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
>>> fib(6)
<generator object fib at 0x03FBC800>
>>> for x in fib(6):
print x
1
1
2
3
5
8
那么有什么区别呢,区别在于执行顺序不同。generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。(待深入理解)
|