加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python中迭代

发布时间:2020-12-20 10:12:27 所属栏目:Python 来源:网络整理
导读:如果给定一个list或tuple,可以使用for循环来遍历,这种遍历称为迭代(Iteration)。python中的迭代是通过for...in 来完成,不仅可迭代list/tuple。还可迭代其他对象。 # 迭代list l = list(range(10)) for item in l: ... print(item) # 迭代dict,由于dict

如果给定一个list或tuple,可以使用for循环来遍历,这种遍历称为迭代(Iteration)。python中的迭代是通过for...in 来完成,不仅可迭代list/tuple。还可迭代其他对象。


# 迭代list
>>> l = list(range(10))
>>> for item in l:
... print(item)

# 迭代dict,由于dict的存储不是像list那样顺序存储,所有迭代结果可能不是按顺序的
>>> d = {'a':1,'b':2}
>>> for key in d: # 默认是迭代的key
... print(key)
...
b
a
>>> for value in d.values(): # 迭代value
... print(value)
...
2
1
>>> for k,v in d.items(): # 迭代key和value
... print(k,v)
...
b 2
a 1

# 迭代字符串
>>> for ch in 'abc':
... print(ch)
...
a
b
c

当使用for时,只要作用与一个迭代对象,就可以正常运行,我们不需要关注迭代对象是list还是其他数据类型。可以通过collections模块的Iterable类型判断一个对象是否是可迭代对象:

>>> from collections import Iterable
>>> isinstance('abc',Iterable) # str类型可迭代
True
>>> isinstance(123,Iterable) # 整数不可迭代
False
>>> dict={'a':1}
>>> isinstance(dict,Iterable) # dict类型可迭代
True


python内置的enumerate函数可以将list变成索引-元素对。这样可以在for中迭代索引和对象本身:

>>> l = ['a','b','c','d']
>>> for i,value in enumerate(l):
... print(i,value)
...
0 a
1 b
2 c
3 d

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读