for
for ... in
lists = [1, 2, 3, 4, 5]
for i in lists:
print(i)
dicts = {
"a": 1,
"b": 2
}
for i in dicts:
print(i)
# 输出结果
a
b
from collections import Iterable
lists = [1, 2, 3, 4, 5]
dicts = {
"a": 1,
"b": 2
}
print(isinstance(lists, Iterable))
print(isinstance(dicts, Iterable))
print(isinstance({"test"}, Iterable))
print(isinstance(1234, Iterable))
# 输出结果
True
True
True
False
lists = [1, 2, 3, 4, 5]
# 看看是不是迭代对象
print(isinstance(enumerate(lists), Iterable))
# 循环
for ind, val in enumerate(lists):
print(ind, val)
# 输出结果
True
0 1
1 2
2 3
3 4
4 5
for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y)
# 输出结果
1 1
2 4
3 9
任何可迭代对象都可以作用于 for 循环,包括我们自定义的数据类型,只要符合迭代条件,就可以使用 for 循环