简体   繁体   中英

Steps in list question, Python beginner

The following code include the last number.

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[::3]
[1, 4, 7, 10]

Why does not includet the last number 2, like 10, 8, 6, 4, 2?

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[:1:-2]
[10, 8, 6, 4]

It seems that the slice operator is simply non-inclusive of the second argument. In other-words, your 1 should be a 0 :

>>> numbers = [1,2,3,4,5,6,7,8,9,10]
>>> numbers[:1:-2]
[10, 8, 6, 4]
>>> numbers[:0:-2]
[10, 8, 6, 4, 2]

Hope that helps :)

For further info, see Note 5 here .

:: is walking over the list with N steps. So it's 1, then it goes to 4, etc. If you want to step with 2 backwards, you want [::-2]

Python is pretty consistent in following the pattern of sequence ranges being lower inclusive, upper exclusive. That is, if you say range(1,5) --> [1,2,3,4]. The lower index is included and the upper is excluded. This helps a lot with various kinds of off-by-one and fencepost errors. See wikipedia for a brief explanation of these kinds of problems.

Because the slice excludes the second number from the range. a[1:4] fetches elements 1, 2 and 3. Likewise, a[10:6:-1] fetches elements 10, 9, 8 and 7, but not 6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM