python -- enumerate()
python -- enumerate()
Again and again,and to the end
今天遇到一个新的函数 enumerate(), 可以从一个可迭代对象(dict,list,string 等)同时得到索引和值,这样就避免了另外生成变量来操作了
>>> l = ["hello","this","is","my","name"]
>>> for index,value in enumerate(l):
... print(index,value)
...
0 hello
1 this
2 is
3 my
4 name
>>> s = "hello"
>>> for index, value in enumerate(s):
... print(index,value)
...
0 h
1 e
2 l
3 l
4 o
还可以接受第二个参数规定初试索引值
>>> for index, value in enumerate(s,1):
... print(index,value)
...
1 h
2 e
3 l
4 l
5 o