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