简体   繁体   English

如何在Python中访问列表的非连续切片

[英]How to access non-consecutive slices of a list in Python

This is a rather basic question as I am new to Python coming from R. 这是一个相当基本的问题,因为我是R的Python新手。

In R we can access non consecutive slices in a vector or list like this: 在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

I am trying to find out how to do the same with a list in Python. 我试图找出如何使用Python中的列表执行相同的操作。

Eg 例如

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

Your advice will be appreciated. 您的建议将不胜感激。

您可以使用a[1:4]+a[7:9]a[1:4,7:9]的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在python中访问列表或字符串的非连续元素 - Accessing non-consecutive elements of a list or string in python Python查找日期列表何时变得不连续 - Python find when list of dates becomes non-consecutive 如何使用 Python 3.5.1 从列表中打印多个非连续值 - How to print multiple non-consecutive values from a list with Python 3.5.1 如何有效计算列表中元素的非连续出现次数? - How to effciently calculate non-consecutive number of appereances of element in list? 如何在python中一次读取文件中的两个非连续行 - How to read two non-consecutive lines in a file once in python 如何计算Python DataFrame中非连续行之间的差异? - How to calculate difference between non-consecutive rows in Python DataFrame? 如何检查一个有序的非连续子序列是否在数组中? 蟒蛇 - How to check if an ordered non-consecutive subsequence is in array? Python Python中多维数组的非连续切片 - Non-consecutive slicing of a multidimensional array in Python IndexError:列表索引超出范围,同时在 python 的列表中查找第一个非连续数字 - IndexError: list index out of range , while finding the first non-consecutive number in a list in python 如何根据熊猫数据框中的非连续索引列表替换值? - How to replace values according to non-consecutive list of indices in pandas dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM