python的迭代

任何可迭代对象都可以用for循环,只要符合迭代条件就可以使用;判断是不是可迭代对象,可以通过判断该对象是不是属于collections模块的Iterable类型,如下:
>>> from collections import Iterable
>>> isinstance('aaa', Iterable)
True
>>>
1、list的迭代
>>> L
[1, 2, 3, 4]
>>> for n in L:
...     print(n)
...
1
2
3
4
>>>
2、tuple的迭代
>>> t = (1,2,3)
>>> for n in t:
...     print(n)
...
1
2
3
>>>
3、dic的迭代
>>> dic = {'a':1, 'b':2, 'c':3}
>>> for n in dic:
...     print(n) #打印每个key
...
a
b
c
>>> for v in dic.values():
...     print(v) #打印每个value
...
1
2
3
>>> for k,v in dic.items():
...     print(k,v) #同时打印每个key和对应value
...
a 1
b 2
c 3
>>>
4、字符串的迭代
>>> for n in 'abcd':
...     print(n)
...
a
b
c
d
5、需要迭代索引的时候,可以使用enumerate()函数
>>> for n in enumerate(['a', 'b', 'c', 'd']):
...     print(n)
...
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
>>> for i,v in enumerate(['a', 'b', 'c', 'd']):
...     print(i,v)
...
0 a
1 b
2 c
3 d
6、还可以同时迭代多个引用变量
>>> for a, b, c in [(1, 2, 3), (4, 5, 6), (7, 8, 9)]:
...     print(a, b, c) #同时打印三个变量
...
1 2 3
4 5 6
7 8 9
>>> for a, b in [(1, 2), (4, 5), (7, 8)]:
...     print(a, b) #同时打印两个变量
...
1 2
4 5
7 8
>>>
>>>> for a, b, c in [(1, 2), (4, 5), (7, 8)]:
...     print(a, b) #参数对不上会报错
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值