10、python高级特性--迭代

迭代

给定一个list或tuple,可以通过for循环来遍历这个list或tuple,这种遍历称为迭代(Iteration)

Python中,迭代是通过for ... in来完成的。

print('----------list迭代---------------')
L = [1, 2, 3]
for l in L:
    print(l)

#dict迭代
#因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样
print('----------dict迭代输出key---------------')
d = {'a': 1, 'b': 2, 'c': 3}

#默认情况下,dict迭代的是key
for key in d:
    print(key)
    
#输出value用 d.values()
print('----------dict迭代输出value---------------')
for value in d.values():
    print(value)
    
#输出key和value用 d.items()
print('----------dict迭代输出key ,value---------------')
for k,v in d.items():
    print(k,v)

#于字符串也是可迭代对象
print('----------字符串迭代---------------')
for ch in 'abc':
    print(ch)

#for循环里,同时引用了两个变量,在Python里是很常见的
print('----------for循环里,同时引用了两个变量---------------')
for x, y in [(1, 1), (2, 4), (3, 9)]:
    print(x, y)
    
    
输出结果:
----------list迭代---------------
1
2
3
----------dict迭代输出key---------------
a
b
c
----------dict迭代输出value---------------
1
2
3
----------dict迭代输出key ,value---------------
a 1
b 2
c 3
----------字符串迭代---------------
a
b
c
----------for循环里,同时引用了两个变量---------------
1 1
2 4
3 9

如果要对list实现类似Java那样的下标循环怎么办?Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:

for i, value in enumerate(['A', 'B', 'C']):
    print(i, value)
    
输出结果:
0 A
1 B
2 C

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

from collections.abc import Iterable 

print(isinstance('abc', Iterable))  # str是否可迭代
print(isinstance([1, 2, 3], Iterable))  # list是否可迭代
print(isinstance(123, Iterable))  # 整数是否可迭代

输出结果:
True
True
False
发布了70 篇原创文章 · 获赞 29 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/LOVEYSUXIN/article/details/103144884