python 中令人困惑的表达式
如果我有列表:
lista=[99, True, "Una Lista", [1,3]]
以下表达式是什么意思?
mi_var = lista[0:4:2]
If I have the list:
lista=[99, True, "Una Lista", [1,3]]
What does the following expression mean?
mi_var = lista[0:4:2]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
语法
lista[0:4:2]
称为 扩展切片语法,返回由索引 0(包含)到 4(不包含)的元素组成的列表切片,但仅包含偶数索引(步长 = 2)。在您的示例中,它将给出
[99, "Una Lista"]
。更一般地,您可以通过编写 lista[::2] 来获取由偶数索引处的每个元素组成的切片。无论列表的长度如何,这都有效,因为开始和结束参数分别默认为 0 和列表的长度。切片的一个有趣功能是,您还可以分配给它们以修改原始列表,或删除切片以从原始列表中删除元素。
The syntax
lista[0:4:2]
is called extended slice syntax and returns a slice of the list consisting of the elements from index 0 (inclusive) to 4 (exclusive), but only including the even indexes (step = 2).In your example it will give
[99, "Una Lista"]
. More generally you can get a slice consisting of every element at an even index by writing lista[::2]. This works regardless of the length of the list because the start and end parameters default to 0 and the length of the list respectively.One interesting feature with slices is that you can also assign to them to modify the original list, or delete a slice to remove the elements from the original list.
从 0 到 3 迭代列表(因为排除了 4,[start, end)),跨过两个元素。结果如预期为
[99, 'Una Lista']
并存储在列表mi_var
中Iterate through the list from 0 to 3 (since 4 is excluded, [start, end)) stepping over two elements. The result of this is
[99, 'Una Lista']
as expected and that is stored in the list,mi_var
一种运行和查看的方法:
它是一个切片表示法,它创建一个新列表,其中包含从索引
0
开始直到但不包括索引的lista
的每个第二个元素4
One way just to run and see:
It's a slice notation, that creates a new list consisting of every second element of
lista
starting at index0
and up to but not including index4