Python 用步长2创建数组的元组

huangapple go评论60阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月6日 03:18:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75354878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定