在 Python 中用两个不连续的切片对列表进行子集化

问题描述 投票:0回答:2

我正在使用 Python 中的列表,我需要提取索引从 0 到 3 和 5 到 7 的元素(

[0:3]
[5:7]
)。可以通过使用切片和连接来完成:

target_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
subset_indx = list(range(3)) + list(range(4, 7)) 
subset_list = [target_list[i] for i in subset_indx]
print(subset_list)  # Output: [1, 2, 3, 5, 6, 7]

我很好奇是否有一种方法可以在 Python 中实现此功能,类似于在 R 中实现此功能。

targetList <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
subsetList <- targetList[c(1:3, 6:7)]

如果有任何见解或可重现的代码示例演示 Pythonic 等效项,我将不胜感激。

python list slice equivalent
2个回答
0
投票

方法一:切片和串联:

subset_list = target_list[:3] + target_list[4:7]

方法二:切片删除:

subset_list = target_list[:7]
del subset_list[3]
# if more than 1 items need to be skipped over, you can also delete a slice, e.g.:
# del subset_list[3:6]

第一种方法可能更Pythonic。


0
投票

您可以尝试的另一种方法是直接在列表理解中创建条件。

target_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
subset_list = [val for i,val in enumerate(target_list) if i in range(0,3) or i in range(4,7) ]

你也可以尝试一下

subset_list = [val for i,val in enumerate(target_list) if i not in range(3,4) and i not in range(7,len(target_list)) ]
© www.soinside.com 2019 - 2024. All rights reserved.