码迷,mamicode.com
首页 > 编程语言 > 详细

python iteration 迭代

时间:2017-12-16 20:29:14      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:ons   python   instance   obj   ati   ble   bytearray   item   values   

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

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

 1 >>> from collections import Iterable
 2 >>> isinstance([1, 2, 3], Iterable)
 3 True
 4 >>> isinstance((1, 2, 3), Iterable)
 5 True
 6 >>> isinstance({one: 1}, Iterable)
 7 True
 8 >>> isinstance(abc, Iterable)
 9 True
10 >>> isinstance(babc, Iterable)
11 True
12 >>> isinstance(bytearray(abc, encoding=utf-8), Iterable)
13 True

二、dict的迭代

 1 >>> d = {one: 1, two: 2}
 2 >>> for key in d:
 3 ...     print(key)
 4 ... 
 5 one
 6 two
 7 >>> for value in d.values():
 8 ...     print(value)
 9 ... 
10 1
11 2
12 >>> for item in d.items():
13 ...     print(item)
14 ... 
15 (one, 1)
16 (two, 2)

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

 1 >>> l = [1, 2, 3]
 2 >>> e = enumerate(l)
 3 >>> e
 4 <enumerate object at 0x101694558>
 5 >>> for index, value in e:
 6 ...     print(index, value)
 7 ... 
 8 0 1
 9 1 2
10 2 3

四、迭代多个变量

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

 

python iteration 迭代

标签:ons   python   instance   obj   ati   ble   bytearray   item   values   

原文地址:http://www.cnblogs.com/gundan/p/8047383.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!