0
点赞
收藏
分享

微信扫一扫

极客编程python入门-迭代


迭代


如果给定一个​list​​tuple​,我们可以通过​for​循环来遍历这个​list​​tuple​,这种遍历我们称为迭代(Iteration)。


Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上。


如何判断一个对象是可迭代对象


集合数据类型,如list、tuple、dict、set、str等


方法是通过collections.abc模块的Iterable类型判断


>>> from collections.abc import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False


只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代:


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


默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values(),如果要同时迭代key和value,可以用for k, v in d.items()。


引用了两个变量,在Python里是很常见的


>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
... print(x, y)
...
1 1
2 4
3 9


极客编程python入门-迭代_迭代


练习

使用迭代查找一个list中最小和最大值,并返回一个tuple:


def findMinAndMax(al):
if len(al) == 0:
return (None, None)

min = al[0]
max = al[0]
for e in al:
if max < e:
max = e
if min > e:
min = e
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('测试成功!')


极客编程python入门-迭代_python_02

举报

相关推荐

0 条评论