廖雪峰 | 4.1 迭代和列表生成式
迭代
1,迭代定义
迭代,Iteration,通过for
循环来遍历这个list
或tuple
,这种遍历我们称为迭代(Iteration)。
2,适用对象
Python中只要是可迭代对象,无论有无下标,都可以迭代。
(所谓下标就是编号,就好比超市中存储柜的编号,通过这个编号就能找到相应的存储空间。 Python中字符串,列表,元祖均支持下标索引)
(1)列表或元组
>>> L= list(range(1, 11))
>>> for n in L:
... print(n)
...
1
2
3
4
5
6
7
8
9
10
(2)字典
默认情况下,dict
迭代的是key
。如果要迭代value
,可以用for value in d.values()
,如果要同时迭代key
和value
,可以用for k, v in d.items()
。
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
... print(key)
...
a
b
c
(3)字符串
>>> for ch in 'ABC':
... print(ch)
...
A
B
C
3,判断可迭代对象:通过collections.abc
模块的Iterable
类型判断
>>> from collections.abc import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False
4,多变量循环
(1)下标循环:enumerate
函数
>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
(2)两变量循环
>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
... print(x, y)
...
1 1
2 4
3 9
5,练习
问:请使用迭代查找一个list
中最小和最大值,并返回一个tuple
# -*- coding: utf-8 -*-
def findMinAndMax(L):
if L == []:
return (None, None)
else:
max = L[0]
min = L[0]
for n in L:
if n >= max:
max = n
if n < min:
min = n
return (min, max)
# 测试
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!')
列表生成式
1,定义
列表生成式即List Comprehensions
,是Python内置的非常简单却强大的可以用来创建list
的生成式。
一般使用[]
2,实例
(1)生成list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
:list(range( , ))
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(2)生成[1x1, 2x2, 3x3, ..., 10x10]
:[x * x for x in range(1, 11)]
语法
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
(3)筛选列表:[表达式 for n in 列表 筛选条件]
#筛选出仅偶数的平方
>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
(4)多层循环
常用两层,三层和三层以上的循环很少用到
#两层循环,生成全排列
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
(5)列出当前目录下的所有文件和目录名:os.listdir()
函数
>>> import os # 导入os模块,模块的概念后面讲到
>>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
['1-100.py', 'abstest.py', 'age.py', 'hanoi.py', 'hello.py', 'if_age.py', 'multest.py', '__pycache__']
(6)将list中所有的字符串变成小写:.lower()
函数
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
(7)使用两个变量来生成list
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
3,列表生成式中的if...else
语法
(1)if ... else
是表达式,而for
后面的if是过滤条件,不能带else
(2)把if写在for
前面必须加else
,否则报错
>>> [x for x in range(1, 11) if x % 2 == 0]
[2, 4, 6, 8, 10]
>>> [x if x % 2 == 0 else -x for x in range(1, 11)]
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
4,练习
问:请修改列表生成式,通过添加if语句保证列表生成式能正确地执行
# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [x.lower() for x in L1 if isinstance(x,str)]
# 测试:
>>> print(L2)
['hello', 'world', 'apple']
`