如何枚举()Python中的元组列表?

时间:2022-10-30 10:19:30

I've got some code like this:

我有一些像这样的代码:

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

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

我被告知有一个enumerate()函数可以为我处理“i”变量:

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?

还是有更优雅的方式?

3 个解决方案

#1


79  

This is a neat way to do it:

这是一个巧妙的方法:

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

#2


3  

This is how I'd do it:

我就是这样做的:

import itertools

letters = [('a', 'A'), ('b', 'B')]
for i, lower, upper in zip(itertools.count(),*zip(*letters)):
    print "Letter #%d is %s/%s" % (i, lower, upper)

EDIT: unpacking becomes redundant. This is a more compact way, which might work or not depending on your use case:

编辑:拆包变得多余。这是一种更紧凑的方式,根据您的使用情况可能有效或无效:

import itertools

letters = [('a', 'A'), ('b', 'B')]
for i in zip(itertools.count(),*zip(*letters)):
    print "Letter #%d is %s/%s" % i

#3


0  

You can do this way too:

你也可以这样做:

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

#1


79  

This is a neat way to do it:

这是一个巧妙的方法:

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

#2


3  

This is how I'd do it:

我就是这样做的:

import itertools

letters = [('a', 'A'), ('b', 'B')]
for i, lower, upper in zip(itertools.count(),*zip(*letters)):
    print "Letter #%d is %s/%s" % (i, lower, upper)

EDIT: unpacking becomes redundant. This is a more compact way, which might work or not depending on your use case:

编辑:拆包变得多余。这是一种更紧凑的方式,根据您的使用情况可能有效或无效:

import itertools

letters = [('a', 'A'), ('b', 'B')]
for i in zip(itertools.count(),*zip(*letters)):
    print "Letter #%d is %s/%s" % i

#3


0  

You can do this way too:

你也可以这样做:

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