如何在 Python 中对元组列表进行 enumerate() ?
我有一些这样的代码:
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”变量:
for i, l in enumerate(['a', 'b', 'c']):
print "%d: %s" % (i, l)
但是,我不知道如何将两者结合起来:如何当相关列表由元组组成时,我使用枚举吗? 我必须这样做吗?
letters = [('a', 'A'), ('b', 'B')]
for i, tuple in enumerate(letters):
(lowercase, uppercase) = tuple
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
或者有更优雅的方式吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个巧妙的方法:
This is a neat way to do it:
这就是我要做的:
编辑:解包变得多余。 这是一种更紧凑的方式,可能有效也可能无效,具体取决于您的用例:
This is how I'd do it:
EDIT: unpacking becomes redundant. This is a more compact way, which might work or not depending on your use case:
你也可以这样做:
You can do this way too:
您还可以编写一个生成器:
然后,它允许您迭代元组(或列表)的集合并解压缩值:
但是,有一个更简单的内置解决方案可以实现此目的。 看看 Richie Hindle 的回答:
You could also write a generator:
Which then allows you to iterate over the collection of tuple (or list) and to unpack the values:
However, there is a simpler built-in solution to achieve this. Have a look at Richie Hindle's answer: