本文着重介绍迭代、可迭代对象、迭代器、生成器几个概念及其应用,先来看那一下这几个概念之间的关系
1.迭代
使用for循环遍历取值的过程叫做迭代。比如使用for循环遍历列表获取值的过程。
for i in [1, 2, 3, 4]:
print(i)
2.可迭代对象
如果一个对象拥有iter方法,那么它就是可迭代对象。可迭代对象可以使用for循环进行遍历取值(也就是迭代)
可以使用isinstance()来判断一个对象是不是可迭代对象
eg:
from collections.abc import Iterable
print(f"列表:{isinstance([], Iterable)}")
print(f"元组:{isinstance((100,), Iterable)}")
print(f"字典:{isinstance({}, Iterable)}")
print(f"集合:{isinstance(set(), Iterable)}")
print(f"字符串:{isinstance('abed', Iterable)}")
print(f"数字:{isinstance(123, Iterable)}")
result:
列表:True
元组:True
字典:True
集合:True
字符串:True
数字:False
3.生成式
3.1 列表生成式
3.1.1 无条件判断的生成式
number_list = [i for i in range(10)]
print(number_list)
result:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3.1.2 有if语句的生成式
number_list = [i for i in range(10) if i % 2 == 0]
print(number_list)
result:
[0, 2, 4, 6, 8]
3.1.3 有if、else语句的生成式
number_list = [i if i % 2 == 0 else i ** 2 for i in range(10)]
print(number_list)
result:
[0, 1, 2, 9, 4, 25, 6, 49, 8, 81]
3.2 集合生成式
集合生成式与 列表生成式差不多,只不过需要将[]换成{}。这里仅举一例
number_set = {i for i in range(10)}
print(number_set)
result:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
3.3 字典生成式
字典生成式与集合生成式差不多,只不过需要里面的元素为key:value的形式。这里仅举一例
number_dict = {i: i % 2 == 0 for i in range(10)}
print(number_dict)
result:
{0: True, 1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False}
3.4 元组生成式
元组生成式与列表生成式差不多,只不过需要将[]换成tuple()。这里仅举一例
number_tuple = tuple(i for i in range(10))
print(number_tuple)
result:
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)