英文:
Python making tuple of an array with a step 2
问题
els = [1, 2, 3, 4, ]
print([(v, els[idx + 1]) for idx, v in enumerate(els[::2])])
为什么Python输出[(1, 2), (3, 3)]
而不是 [(1, 2), (3, 4)]
?
PS:我知道我可以这样做:[(els[i], els[i + 1]) for i in range(0,len(els),2)]
我不是要求解决方案,我只是想知道为什么。
英文:
els = [1, 2, 3, 4, ]
print([(v, els[idx + 1]) for idx, v in enumerate(els[::2])])
Why does Python output [(1, 2), (3, 3)]
instead of [(1, 2), (3,
4)]
?
PS: I know I could do this: [(els[i], els[i + 1]) for i in range(0,len(els),2)]
I'm not asking for a solution, I'm asking why is this?
答案1
得分: 2
why is this?
为什么会这样?
Take closer look at enumerate(els[::2])
, consider following simple code
仔细看看 enumerate(els[::2])
,考虑以下简单的代码
els = [1,2,3,4,5,6,7,8,9]
for elem in enumerate(els[::2]):
print(elem)
gives output
输出如下
(0, 1)
(1, 3)
(2, 5)
(3, 7)
(4, 9)
Observe that numbering was applied after slicing but you are using index to access element of list before slicing and they are not in unison.
注意,编号是在切片之后应用的,但您在切片之前使用索引访问列表元素,它们不是一致的。
英文:
> why is this?
Take closer look at enumerate(els[::2])
, consider following simple code
els = [1,2,3,4,5,6,7,8,9]
for elem in enumerate(els[::2]):
print(elem)
gives output
(0, 1)
(1, 3)
(2, 5)
(3, 7)
(4, 9)
Observe that numbering was applied after slicing but you are using index to access element of list before slicing and they are not in unison.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论