可迭代的类型:list,tuple,dict,str,bytes,bytearray等
一、怎么判断一个对象是否可迭代
1 >>> from collections import Iterable 2 >>> isinstance([1, 2, 3], Iterable) 3 True 4 >>> isinstance((1, 2, 3), Iterable) 5 True 6 >>> isinstance({‘one‘: 1}, Iterable) 7 True 8 >>> isinstance(‘abc‘, Iterable) 9 True 10 >>> isinstance(b‘abc‘, Iterable) 11 True 12 >>> isinstance(bytearray(‘abc‘, encoding=‘utf-8‘), Iterable) 13 True
二、dict的迭代
1 >>> d = {‘one‘: 1, ‘two‘: 2} 2 >>> for key in d: 3 ... print(key) 4 ... 5 one 6 two 7 >>> for value in d.values(): 8 ... print(value) 9 ... 10 1 11 2 12 >>> for item in d.items(): 13 ... print(item) 14 ... 15 (‘one‘, 1) 16 (‘two‘, 2)
三、list迭代索引和元素--利用Python内置的enumerate
函数可以把一个list变成索引-元素对
1 >>> l = [1, 2, 3] 2 >>> e = enumerate(l) 3 >>> e 4 <enumerate object at 0x101694558> 5 >>> for index, value in e: 6 ... print(index, value) 7 ... 8 0 1 9 1 2 10 2 3
四、迭代多个变量
1 >>> for x, y in [(1, 1), (2, 4), (3, 9)]: 2 ... print(x, y) 3 ... 4 1 1 5 2 4 6 3 9
时间: 2024-10-09 00:48:08