谈谈python中的遍历
2016-03-10 17:13
471 查看
谈谈python中的遍历
python中也有像java中的for...each...。在python中是for...in... 其实感觉差不多,不过python的规则更灵活一点,
只要是可以进行迭代的对象都能使用for...in...。那么问题来了,什么是可迭代的对象呢?可以使用collections模块的Iterable来判断。
list的迭代就不说了。dict也可以迭代大家没想到吧,看例子
output:
name
age
这是迭代key的,当然也可以迭代value的,key和value同时迭代也是可以的,不过in后面的需要改一下
最后一个小问题,如果要对list实现类似Java那样的下标循环怎么办?
Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身。
output:
0 1
1 2
2 3
3 4
还有个有趣的现象
python是不是很智能,不过也很容易有歧义。你要问我怎么获取每个tuple中的第一个元素,那我想说我也不会啊!
python中也有像java中的for...each...。在python中是for...in... 其实感觉差不多,不过python的规则更灵活一点,
只要是可以进行迭代的对象都能使用for...in...。那么问题来了,什么是可迭代的对象呢?可以使用collections模块的Iterable来判断。
from collections import Iterable flag = isinstance('adc',Iterable) print(flag) flag = isinstance(123,Iterable) print(flag)
list的迭代就不说了。dict也可以迭代大家没想到吧,看例子
d = {'name':'wang','age':20} for key in d: print(key)
output:
name
age
这是迭代key的,当然也可以迭代value的,key和value同时迭代也是可以的,不过in后面的需要改一下
d = {'name':'wang','age':20} for k,v in d.items():#迭代value时是d.values print(k,v)
最后一个小问题,如果要对list实现类似Java那样的下标循环怎么办?
Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身。
list = [1,2,3,4] for i,n in enumerate(list): print(i,n)
output:
0 1
1 2
2 3
3 4
还有个有趣的现象
list = [(1,2),(3,4),(5,6)] for x,y in list: print(x,y) output: 1,2 3,4 5,6 for x in list: print(x) output: (1,2) (3,4) (5,6)
python是不是很智能,不过也很容易有歧义。你要问我怎么获取每个tuple中的第一个元素,那我想说我也不会啊!
相关文章推荐
- [Leetcode]@python 107. Binary Tree Level Order Traversal II
- [Leetcode]@python 106. Construct Binary Tree from Inorder and Postorder Traversal
- python代码格式检查工具部署pre_commit
- Python讀寫Excel文件的實例
- numpy.hstack(tup)
- numpy.random.uniform(记住文档网址)
- Windows下Python的Django框架环境部署及应用编写入门
- Python格式化日期时间的函数
- ascii' codec can't encode characters in position 598-599: ordinal not in range(128)解决方案
- python读写excel
- Python实例讲解 -- 获取本地时间日期(日期计算)
- java + spring (jython\python\script) Error:SyntaxError: no viable alternative at character '\n'
- Java调用Python返回乱码问题解决
- python sqlite3 mysql
- 002_第三部分_[函数 / 高阶函数 / 装饰器]
- python——读写excel
- 【Python】《大话设计模式》Python版代码实现
- 【python】gevent学习
- 【Python】Python中的深浅拷贝
- 【python】编程语言入门经典100例--36