如何用在python中迭代一个列表以及字典的索引和值?

本文摘自《编写高质量代码,改善python程序的91个建议》大家有兴趣的可以看看本书。其中列出了很多非常实用的建议。

对序列进行迭代并获取序列中的元素。

方法一:在每次循环中对索引变量进行自增

li = ['a', 'b', 'c', 'd', 'e']
index = 0
for i in li:
  print "index":,index, "element":, i
  index +=1

方法二 使用range()和len()方法结合。


li = ['a', 'b', 'c', 'd', 'e']
for i in range(len(li)):
    print "inde:", i, "element:", li[i]

方法三: 使用while循环,用len()获取循环次数。

li = ['a', 'b', 'c', 'd', 'e']
indx = 0
while index < len(li)
    print "index:", index, "element:", li[index]
    index += 1

方法四:使用zip()

li = ['a', 'b', 'c', 'd', 'e']
for i e in zip(range(len(i)), li):
    print "index:", i, "element:", e

方法5: 使用enumerate()获取序列迭代的索引和值

li = ['a', 'b', 'c', 'd', 'e']
for i, e in enumerate(li):
    print "index:", i, "element:", e

enumerate()函数的内部实现机制也比较简单,enumerate(sequence, start=0)实际相当于如下的代码

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

利用此特性用户可以实现自己的enumerate()函数。比如,myenumerate()以反序的方式获取序列的索引和值

def myenumerate(sequence):
    n = -1
    for elem in reversed(sequence):
        yield len(sequence)+n ,elem
        n = n-1
li = ['a', 'b', 'c', 'd', 'e']
for i, e in myenumerate(li):
    print "index:", i, "element:", e

注:要获取字典中key和value应该使用iteritems()f方法:

personinfo = {'name': 'Jon', 'age': '20', 'hobby': 'football'}

for k, v in personinfo.iteritems():
    print k, ":", v
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值