一、迭代
python中如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:
>>> from collections import Iterable >>> isinstance(‘abc‘, Iterable) # str是否可迭代 True >>> isinstance([1,2,3], Iterable) # list是否可迭代 True >>> isinstance(123, Iterable) # 整数是否可迭代 False
Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:
>>> for i, value in enumerate([‘A‘, ‘B‘, ‘C‘]): ... print i, value ... 0 A 1 B 2 C
>>> for x, y in [(1, 1), (2, 4), (3, 9)]: ... print x, y ... 1 1 2 4 3 9
>>> d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ } >>> for k, v in d.iteritems(): ... print k, ‘=‘, v ... y = B x = A z = C
二、列表生成式
要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用range(1, 11):
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
如果要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?方法一是循环:
如果要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?方法一是循环:
>>> L = [] >>> for x in range(1, 11): ... L.append(x * x) ... >>> L [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
如果要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?方法二是列表生成式:
>>> [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:
>>> [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100]
还可以使用两层循环,可以生成全排列:
>>> [m + n for m in ‘ABC‘ for n in ‘XYZ‘] [‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘]
列出当前目录下的所有文件和目录名:
>>> import os>>> [d for d in os.listdir(‘.‘)]# os.listdir可以列出文件和目录[‘DLLs‘, ‘Doc‘, ‘geckodriver-v0.11.1-win64.zip‘, ‘geckodriver.exe‘, ‘include‘, ‘Lib‘, ‘libs‘, ‘pip-8.1.2‘, ‘pip-8.1.2.tar.gz‘, ‘python.exe‘, ‘python2.7.exe‘, ‘python2.exe‘, ‘pythonw.exe‘, ‘pythonw2.7.exe‘, ‘pythonw2.exe‘, ‘Scripts‘, ‘selenium‘, ‘setuptools-28.7.1‘, ‘setuptools-28.7.1.zip‘, ‘tcl‘, ‘Tools‘, ‘w9xpopen.exe‘]
列表生成式也可以使用两个变量来生成list:
>>> d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ } >>> [k + ‘=‘ + v for k, v in d.iteritems()] [‘y=B‘, ‘x=A‘, ‘z=C‘]
三、生成器
在Python中,一边循环一边计算的的机制称为生成器(Generator)
1.创建Generator,只要把一个列表生成式的[]改成(),如下:
>>> L = [x * x for x in range(10)] >>> L [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> g = (x * x for x in range(10)) >>> g <generator object <genexpr> at 0x104feab40> 2.打印Generator的元素,可以通过generator的next()方法
>>> g.next() 0 >>> g.next() 1 >>> g.next() 4 >>> g.next() 9 >>> g.next() 16 >>> g.next() 25 >>> g.next() 36 >>> g.next() 49 >>> g.next() 64 >>> g.next() 81 >>> g.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration generator保存的是算法,每次调用next(),就计算出下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误, 还可使用for循环,因为generator也是可迭代对象,如下:
>>> g = (x * x for x in range(10)) >>> for n in g: ... print n ... 0 1 4 9 16 25 36 49 64 81
时间: 2024-11-03 22:20:23