Python 3-列表切片-查找给定元素并返回列表的切片[elem-10:elem + 10])

时间:2018-10-23 15:55:25

标签: python-3.x list slice

我正在处理一个字符串列表。 我想查找给定元素的列表,如果找到,我想返回从切片前的n个索引到找到的元素后的n个索引的列表切片。

str_list = ['str1','str2','str3','str4','str5','str6','str7','str8']
for i in str_list:
    for elem in str_list:
        if '5' in elem:
            print(elem in range(str_list[i-2:i+3]))

#expected output
['str3','str4','str5','str6','str7']

2 个答案:

答案 0 :(得分:1)

尝试一下:

str_list = ['str1','str2','str3','str4','str5','str6','str7','str8']

for c,i in enumerate(str_list):
    if '5' in i:
        new = str_list[c-2:c+3]

In [1068]: new
Out[1068]: ['str3', 'str4', 'str5', 'str6', 'str7']

答案 1 :(得分:0)

您可以enumerate列表并遍历列表,从而在与您的条件相符的每个元素上产生一个切片:

def slices(sequence, radius, condition):
    for i, x in enumerate(sequence):
        if condition(x):
            begin = i - radius
            begin = 0 if begin < 0 else begin
            end = i+radius+1
            yield sequence[begin:end]

print(list(slices(str_list, 2, lambda s: '5' in s)))
# [['str3', 'str4', 'str5', 'str6', 'str7']]