Python:解包内部嵌套元组/列表,同时仍获取其索引号 [英] Python: Unpacking an inner nested tuple/list while still getting its index number

查看:52
本文介绍了Python:解包内部嵌套元组/列表,同时仍获取其索引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉使用enumerate():

<预><代码>>>>seq_flat = ('A', 'B', 'C')>>>对于 num,在 enumerate(seq_flat) 中输入:打印编号,条目0 安1 乙2 C

我希望能够对嵌套列表执行相同的操作:

<预><代码>>>>seq_nested = (('A', 'Apple'), ('B', 'Boat'), ('C', 'Cat'))

我可以打开它:

<预><代码>>>>对于字母,seq_nested 中的单词:打印字母、单词一个苹果B船C猫

我应该如何打开它以获得以下内容?

0 一个苹果1 B 船2 C 猫

我知道的唯一方法是使用计数器/增量器,据我所知,这是非 Pythonic 的.有没有更优雅的方法呢?

解决方案

for i, (letter, word) in enumerate(seq_nested):打印 i,字母,单词

I am familiar with using enumerate():

>>> seq_flat = ('A', 'B', 'C')
>>> for num, entry in enumerate(seq_flat):
        print num, entry
0 A
1 B
2 C

I want to be able to do the same for a nested list:

>>> seq_nested = (('A', 'Apple'), ('B', 'Boat'), ('C', 'Cat'))

I can unpack it with:

>>> for letter, word in seq_nested:
        print letter, word
A Apple
B Boat
C Cat

How should I unpack it to get the following?

0 A Apple
1 B Boat
2 C Cat

The only way I know is to use a counter/incrementor, which is un-Pythonic as far as I know. Is there a more elegant way to do it?

解决方案

for i, (letter, word) in enumerate(seq_nested):
  print i, letter, word

这篇关于Python:解包内部嵌套元组/列表,同时仍获取其索引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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