迭代——python笔记

迭代

 

通过collections模块的Iterable类型判断是否可迭代对象:

>>> from collections import Iterable

>>> isinstance('abc', Iterable) # str是否可迭代

True

>>> isinstance([1,2,3], Iterable) # list是否可迭代

True

>>> isinstance(123, Iterable) # 整数是否可迭代

False

 

isinstancePython中的一个内建函数。是用来判断一个对象的变量类型。

>>> x = 'abc'

>>> y = 123

>>> isinstance(x, str)

True

>>> isinstance(y, str)

False

 

Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:

>>> for i, value in enumerate(['A', 'B', 'C']):

...     print(i, value)

...

0 A

1 B

2 C

 

for循环里,同时引用了两个变量,在Python里是很常见的,比如下面的代码:

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

...     print(x, y)

...

1 1

2 4

3 9

猜你喜欢

转载自blog.csdn.net/qq_36230524/article/details/82735329