判断对象是否可迭代:
通过collections模块的Iterable类型判断,引入collections模块,调用isinstance(xxx, Iterable)方法,返回bool类型。
from collections import Iterable
print(isinstance("你好!", Iterable)) -------> True
print(isinstance(792, Iterable)) -------> False
print(isinstance([7, 9, 2], Iterable)) -------> True
print(isinstance((7, 9, 2), Iterable)) -------> True
print(isinstance({"a": 1, "b": 2, "c":3}, Iterable)) -------> True
字符串、list、tuple、字典都可以遍历。
遍历字典:
语句
解释
for k in dic:
遍历key
for v in dic.values():
遍历value
for k, v in dic.items():
遍历key和value
遍历list需要用到下标时,可以用enumerate函数:
for i, v in enumerate(["a", "b", "c"]):
print("第%d个是%s" % (i, v))
---------------------------------------
第0个是a
第1个是b
第2个是c
二维数组遍历:
for x, y in [[1, 2], [3, 4], [5, 6]]:
print(x, y)
---------------------------------------
(1, 2)
(3, 4)
(5, 6)
list生成式:用[...for...in...]语句生成list
mi = [x*x*x for x in range(0, 10)]
print(mi) -----------> [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
qishu = [x for x in range(0, 20) if x % 2 != 0]
print(qishu) -----------> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
he = [x+"="+y for x in "ABC" for y in "abc"]
print(he) -----------> ['A=a', 'A=b', 'A=c', 'B=a', 'B=b', 'B=c', 'C=a', 'C=b', 'C=c']