根据其他嵌套列表对嵌套列表进行切片

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

我正在尝试使用其他子列表(slc)中的元素对子列表(arr)进行切片。我正在使用Python。如果子列表上没有重复的值来切片(arr),我的代码工作得很好,两种情况我都无法获取块。 arr[0] 必须使用 slc[0] 进行切片,arr[1] 必须使用 slc[1] 进行切片,并且 arr[2] 必须用 slc[2] 进行切片。

这是一个示例和我现在正在使用的代码。

arr=[ [5, 9, 8, 1, 0, 10, 11, 5], [13, 4, 13, 2, 5, 6, 13], [8, 25, 13, 9, 8, 7]]

slc=[[0, 5] , [5, 13], [13, 7]]

rslt=[]

for i in range(len(arr)):
    rslt.append(arr[i][arr[i].index(slc[i][0]):arr[i].index(slc[i][1])+1])

当前结果:

rlst=[[], [], [13, 9, 8, 7]]

预期结果:

rlst=[[0, 10, 11, 5], [5, 6, 13], [13, 9, 8, 7]] #expected results

我当前的代码不适用于

arr[0]
arr[1]
,因为
slc[0]
slc[1]
分别有来自
arr[0]
arr[1]
的多个元素,因此切片程序无法正常工作。

提前致谢。

python slice chunks
2个回答
1
投票

list.index()
允许您指定开始搜索的起始索引。因此,在查找结束索引时,请使用第一项的索引作为此参数。

for a, (start, end) in zip(arr, slc):
    slice_start = a.index(start)
    slice_end = a.index(end, slice_start + 1)
    rslt.append(a[slice_start:slice_end + 1])

如果要切片直到

slc
中第二个值的最后一次出现,请使用
rindex()
而不是
index()

for a, (start, end) in zip(arr, slc):
    slice_start = a.index(start)
    slice_end = a.rindex(end)
    rslt.append(a[slice_start:slice_end + 1])

0
投票
arr=[ [5, 9, 8, 1, 0, 10, 11, 5], [13, 4, 13, 2, 5, 6, 13], [8, 25, 13, 9, 8, 7]]

slc=[[0, 5] , [5, 13], [13, 7]]

rslt=[]

for i, x in enumerate(arr):

    # start index
    st_idx = x.index(slc[i][0])

    # create a sub list from start index to rest of the list
    sub = x[st_idx:]    
    
    # end index is taken from the sublist
    end = sub.index(slc[i][1])

    # end index is taken as end + 1 as you need end value to be in the list
    rslt.append(sub[:end+1])

print(rslt)

# Output : [[0, 10, 11, 5], [5, 6, 13], [13, 9, 8, 7]]
© www.soinside.com 2019 - 2024. All rights reserved.