美文网首页Python基础
[python基础]-11 高级特性-迭代

[python基础]-11 高级特性-迭代

作者: 一点想法 | 来源:发表于2019-07-18 15:44 被阅读0次

1.迭代

  • 定义

给定一个列表或者元祖,可以通过for循环来遍历每一个元素,进而对元素做进一步的操作,这种遍历称为迭代(Iteration)

  • 特性
  1. python中可迭代的对象区别于C语言,C语言数组是通过下标进行迭代,但是python不同,即使迭代对象没有下标,类似字典数据类型,也可进行迭代,即python只要是可迭代对象就可以迭代
d = {'a': 1, 'b': 2, 'c': 3}    定义一个字典d
>>>for key in d:
...   print(key)
a
b
c

  1. 如何判断一个对象是否可以进行迭代操作,可以使用collectons模块的Iterable类型进行判断
from collections import Iterable
>>> isinstance('abc',Iterable)
True      #str可以迭代
>>>isinstance([1,2,3],Iterable)
True    #list可以迭代
>>>isinstance(123,Iterable)
False   #int类型不可迭代

相关文章

网友评论

    本文标题:[python基础]-11 高级特性-迭代

    本文链接:https://www.haomeiwen.com/subject/xsktlctx.html