如何在Python中的元组列表中枚举()? [英] How do I enumerate() over a list of tuples in Python?

查看:272
本文介绍了如何在Python中的元组列表中枚举()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的代码:

letters = [('a', 'A'), ('b', 'B')]
i = 0
for (lowercase, uppercase) in letters:
    print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
    i += 1

有人告诉我,有一个enumerate()函数可以为我处理"i"变量:

I've been told that there's an enumerate() function that can take care of the "i" variable for me:

for i, l in enumerate(['a', 'b', 'c']):
    print "%d: %s" % (i, l)

但是,我不知道如何将两者结合起来:当有问题的列表由元组组成时,如何使用枚举?我必须这样做吗?

However, I can't figure out how to combine the two: How do I use enumerate when the list in question is made of tuples? Do i have to do this?

letters = [('a', 'A'), ('b', 'B')]
for i, tuple in enumerate(letters):
    (lowercase, uppercase) = tuple
    print "Letter #%d is %s/%s" % (i, lowercase, uppercase)

还是有一种更优雅的方式?

Or is there a more elegant way?

推荐答案

这是一种简洁的方法:

letters = [('a', 'A'), ('b', 'B')]
for i, (lowercase, uppercase) in enumerate(letters):
    print "Letter #%d is %s/%s" % (i, lowercase, uppercase)

这篇关于如何在Python中的元组列表中枚举()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆