[英]Nested list comprehension with enumerate build-in function
I studying list comprehension and I stuck in the following code: 我研究列表理解,并坚持下面的代码:
[[c for c in enumerate(r)] for r in enumerate(['a','b','c'])]
which returns: 返回:
[[(0, 0), (1, 'a')], [(0, 1), (1, 'b')], [(0, 2), (1, 'c')]]
However, I was expecting this: 但是,我期望这样:
[[(0,(0,'a'))],[(1,(1,'b'))],[(2,(2,'c'))]]
I read some articles but could not understand the prompted output. 我阅读了一些文章,但无法理解提示的输出。 Someone can explain it to me, please.
请有人可以向我解释。
You are enumerating each individual element of the outer enumerate()
: 您正在枚举外部
enumerate()
每个元素 :
You create one enumerate()
over the list ['a', 'b', 'c']
, this produces a sequence of tuples with (counter, letter)
. 您在列表
['a', 'b', 'c']
创建一个enumerate()
,这将生成一个带有(counter, letter)
的元组序列。
You then apply enumerate()
to each of the (counter, letter)
tuples, producing (0, count)
and (1, letter)
tuples each . 然后应用
enumerate()
到各的(counter, letter)
的元组,生产(0, count)
和(1, letter)
元组的每个 。
So in the end you get the following element for each of the letters in the list ['a', 'b', 'c']
: 因此,最后,对于列表
['a', 'b', 'c']
中的每个字母,您都会获得以下元素:
[
[(0, 0), (1, 'a')], # enumerate((0, 'a'))
[(0, 1), (1, 'b')], # enumerate((1, 'b'))
[(0, 2), (1, 'c')], # enumerate((2, 'c'))
]
If you wanted to get (counter, (counter, element))
, you need to apply enumerate()
to the whole output of enumerate()
, not to each individual tuple: 如果你想获得
(counter, (counter, element))
您需要申请enumerate()
以全输出 enumerate()
而不是每一个人的元组:
>>> [combo for combo in enumerate(enumerate(['a','b','c']))]
[(0, (0, 'a')), (1, (1, 'b')), (2, (2, 'c'))]
You could just call list()
on enumerate()
too: 您也可以在
enumerate()
上调用list()
:
>>> list(enumerate(enumerate(['a','b','c'])))
[(0, (0, 'a')), (1, (1, 'b')), (2, (2, 'c'))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.