How do I enumerate() over a list of tuples in Python?

你说的曾经没有我的故事 提交于 2019-11-27 01:27:24

问题


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:

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?


回答1:


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:


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:


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])


来源:https://stackoverflow.com/questions/849369/how-do-i-enumerate-over-a-list-of-tuples-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!