python 中令人困惑的表达式

发布于 2024-09-29 00:48:56 字数 145 浏览 5 评论 0原文

如果我有列表:

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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你对谁都笑 2024-10-06 00:48:56

语法 lista[0:4:2] 称为 扩展切片语法,返回由索引 0(包含)到 4(不包含)的元素组成的列表切片,但仅包含偶数索引(步长 = 2)。

在您的示例中,它将给出 [99, "Una Lista"]。更一般地,您可以通过编写 lista[::2] 来获取由偶数索引处的每个元素组成的切片。无论列表的长度如何,这都有效,因为开始和结束参数分别默认为 0 和列表的长度。

切片的一个有趣功能是,您还可以分配给它们以修改原始列表,或删除切片以从原始列表中删除元素。

>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[::2] = ['a', 'b', 'c', 'd', 'e']   # Assign to index 0, 2, 4, 6, 8
>>> x
['a', 1, 'b', 3, 'c', 5, 'd', 7, 'e', 9]
>>> del x[:5]                            # Remove the first 5 elements
>>> x
[5, 'd', 7, 'e', 9]

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.

>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[::2] = ['a', 'b', 'c', 'd', 'e']   # Assign to index 0, 2, 4, 6, 8
>>> x
['a', 1, 'b', 3, 'c', 5, 'd', 7, 'e', 9]
>>> del x[:5]                            # Remove the first 5 elements
>>> x
[5, 'd', 7, 'e', 9]
ゃ人海孤独症 2024-10-06 00:48:56

从 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

寄风 2024-10-06 00:48:56

一种运行和查看的方法:

>>> lista=[99, True, "Una Lista", [1,3]]
>>> lista[0:4:2]
[99, 'Una Lista']

它是一个切片表示法,它创建一个新列表,其中包含从索引 0 开始直到但不包括索引的 lista 的每个第二个元素4

One way just to run and see:

>>> lista=[99, True, "Una Lista", [1,3]]
>>> lista[0:4:2]
[99, 'Una Lista']

It's a slice notation, that creates a new list consisting of every second element of lista starting at index 0 and up to but not including index 4

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文