【问题标题】:How to access non-consecutive slices of a list in Python如何在 Python 中访问列表的非连续切片
【发布时间】:2018-05-08 22:19:52
【问题描述】:

这是一个相当基本的问题,因为我是来自 R 的 Python 新手。

在 R 中,我们可以像这样访问向量或列表中的非连续切片:

> a = 1:10
> a[c(2:4, 7:9)]
[1] 2 3 4 7 8 9
> list_a = list(1:10)
> list_a[[1]][c(2:4, 7:9)]
[1] 2 3 4 7 8 9

我正在尝试找出如何在 Python 中对列表执行相同操作。

例如

a = list(range(20))
a[1:4]
# returns
[1, 2, 3]
# but the following syntax creates an exception:
a[1:4, 7:9]

您的建议将不胜感激。

【问题讨论】:

标签: python indexing slice


【解决方案1】:

您可以使用a[1:4]+a[7:9]a[1:4,7:9] 中完成您想要的操作。

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2023-03-13
    • 2018-02-23
    • 2017-08-09
    • 2019-11-01
    • 2014-10-14
    • 1970-01-01
    • 2019-12-01
    相关资源
    最近更新 更多