可迭代的类型:list,tuple,dict,str,bytes,bytearray等

一、怎么判断一个对象是否可迭代

 >>> from collections import Iterable
>>> isinstance([1, 2, 3], Iterable)
True
>>> isinstance((1, 2, 3), Iterable)
True
>>> isinstance({'one': 1}, Iterable)
True
>>> isinstance('abc', Iterable)
True
>>> isinstance(b'abc', Iterable)
True
>>> isinstance(bytearray('abc', encoding='utf-8'), Iterable)
True

二、dict的迭代

 >>> d = {'one': 1, 'two': 2}
>>> for key in d:
... print(key)
...
one
two
>>> for value in d.values():
... print(value)
...
1
2
>>> for item in d.items():
... print(item)
...
('one', 1)
('two', 2)

三、list迭代索引和元素--利用Python内置的enumerate函数可以把一个list变成索引-元素对

 >>> l = [1, 2, 3]
>>> e = enumerate(l)
>>> e
<enumerate object at 0x101694558>
>>> for index, value in e:
... print(index, value)
...
0 1
1 2
2 3

四、迭代多个变量

 >>> for x, y in [(1, 1), (2, 4), (3, 9)]:
... print(x, y)
...
1 1
2 4
3 9

最新文章

  1. 反射,System.Type类
  2. 循环多次ajax请求
  3. atitit.提升软件开发的效率and 质量的那些强大概念and方法总结
  4. java系统库性能优化注意点
  5. maven中的 dependencies 和 dependencyManagement 的区别
  6. Activiti系列: 如何在web中使用activiti和sql server
  7. Asp.Net--回调技术
  8. 电子工程师名片——UFI Command,USB盘符的显示
  9. QT4.8.5 连接数据库(读写数据)
  10. 20164318 毛瀚逸-----EXP5 MSF基础应用
  11. 通用mapper版+SpringBoot+MyBatis框架+mysql数据库的整合
  12. Linux常用命令之链接命令和权限管理命令
  13. drop all database objects
  14. ITxlab倡议启动“互联网X大脑”计划
  15. A星寻路算法入门(Unity实现)
  16. 在Android.mk文件中输出打印消息
  17. Java集合--概述
  18. Python实现类似JavaScript 的Json对象
  19. C#程序集系列07,篡改程序集
  20. grub2 详解

热门文章

  1. require.js结合项目的使用心得
  2. cocoaPods 安装和应用
  3. XenServer网卡Bonding
  4. Android(Linux)模拟按键、触摸屏等事件
  5. Vim经常使用技巧总结2
  6. 信雅达面试题atoi函数实现
  7. huawei校招测试题
  8. Why there are no job running on hadoop
  9. Linux系统(Centos)下安装Java环境配置步骤详述
  10. 获取Android系统应用信息