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

老子叫甜甜 提交于 2019-11-28 06:43:35

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)

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

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