|
发表于 2021-11-18 19:04:02
|
显示全部楼层
本楼为最佳答案
本帖最后由 傻眼貓咪 于 2021-11-18 19:05 编辑
可迭代对象
可迭代(Iterable) 对象是数组的泛化。这个概念是说任何对象都可以被定制为可在 for 循环中使用的对象。例如字符串也是可迭代的。
Python 的 4 种序列:
列表(list)
集合(set)
元祖(tuple)
字典(dictionary)
Python 字符串(string)
*以上序列和字符串都可迭代(被视为可迭代对象)
例子 1:序列- a = ['a', 'b', 'c', 'd', 'e'] # 列表
- b = ('a', 'b', 'c', 'd', 'e') # 元祖
- c = {'a', 'b', 'c', 'd', 'e'} # 集合
- d = {'one': 'a', 'two': 'b', 'three': 'c', 'four': 'd', 'five': 'e'} # 字典
- for i in a:
- print(i, end = " ")
- print()
- for i in b:
- print(i, end = " ")
- print()
- for i in c:
- print(i, end = " ")
- print()
- for i in d.items():
- print(i, end = " ")
- print()
复制代码 输出结果:- a b c d e
- a b c d e
- c d a e b
- ('one', 'a') ('two', 'b') ('three', 'c') ('four', 'd') ('five', 'e')
复制代码 以上你会发现,除了集合(set)每次不按照顺序输出之外,其他都是有序输出的。这是因为集合(set)是无序的;列表和元祖是有序的,而字典虽说是无序(属於 Hash 的一种)但是当访问时,如 items()、keys()、或values()都会变成有序的(这是因为 Python 3.6 版本之后,字典插入 indices 索引(OderedDict 元素)变得有序。而之前的 2.6 版本字典是乱序的,相关讲解可到 Python 官方自行查询)
例子 2:字符串- arr = "bananaAPPLEflower"
- for i in arr:
- print(i, end = " ")
复制代码 输出结果:- b a n a n a A P P L E f l o w e r
复制代码
除了上述以外,也可以自定义迭代器(定义一个迭代对象),如:- def myFunction():
- i = 10
- while i > 0:
- i -= 1
- yield i # yield 用于迭代
- a = myFunction()
- for i in a:
- print(i, end = " ")
复制代码 输出结果:迭代本身也有可用函数,如;iter()、next()等,这些网络可查询相关用法,这里就不多讲了。 |
|