Python高级特性(二)

迭代

如果给定一个 list 或 tuple,我们可以通过 for 循环来遍历这个 list 或
tuple,这种遍历我们称为迭代。Python 的 for 循环不仅可以用在 list 或 tuple 上,还可以作用在其他可迭代对象上。list 这种数据类型虽然有下标,但很多其他数据类型是没有下标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,比如 dict 就可以迭代:

>>> d = {'a':1,'b':2,'c':3}
>>> for i in d:
	print(i)

因为 dict 的存储不是按照 list 的方式顺序排列,所以,迭代出的结果顺
序很可能不一样。
所以,当我们使用 for 循环时,只要作用于一个可迭代对象,for 循环
就可以正常运行,而我们不太关心该对象究竟是 list 还是其他数据类型。
那么,如何判断一个对象是可迭代对象呢?方法是通过 collections 模块
的 Iterable 类型判断:

>>> from collections.abc import Iterable
>>> isinstance('abc',Iterable)
True
>>> isinstance([1,2,3],Iterable)
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

列表生成式

列表生成式即 List Comprehensions,是 Python 内置的非常简单却强大的
可以用来创建 list 的生成式。举个例子,要生成 list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用 list(range(1, 11)):

>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

如果要得到x2的列表,则:

>>> for i in range(1,11):
	L.append(i * i)
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

但是循环太繁琐,而列表生成式则可以用一行语句代替循环生成上面的
list:

>>> [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 % 4 == 0]
[16, 64]

还可以使用两层循环,可以生成全排列:

>>> [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('.')]
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']

如果 list 中既包含字符串,又包含整数,由于非字符串类型没有 lower()
方法,所以列表生成式会报错:

>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'

使用内建的 isinstance 函数可以判断一个变量是不是字符串:

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False

请修改列表生成式,通过添加 if 语句保证列表生成式能正确地执行:

>>> list = ['Hello','World',18,'Apple',None]
>>> [s.lower() for s in list if isinstance(s,str)]
['hello', 'world', 'apple']

运用列表生成式,可以快速生成list,可以通过一个list推导出另一个list,
而代码却十分简洁。

发布了37 篇原创文章 · 获赞 42 · 访问量 4513

猜你喜欢

转载自blog.csdn.net/qq_43337175/article/details/104357258