我有一个这样的列表
lst = ['a','a','a','X','y','y','y','a','a','y','y','a','a','a','a','a','a','X','y','a','y','a','y','y','y','a','a','a','a']
任务是获取此输出
lst = ['a','a','a','X','y','y','y','y','y','y','y','a','a','a','a','a','a','X','y','y','y','y','y','y','y','a','a','a','a']
说明:只需在下一个X之前找到X和最后一个y,然后将y之间的a值替换为y。如果末尾没有下一个X,则考虑最后一个y。
我试图找到起始索引和结束索引
starts = [i for i, x in enumerate(lst) if x == 'X']
[3,17]
ends = [i for i, x in enumerate(lst) if x == 'y']
[4、5、6、9、10、18、20、22、23、24]
,然后循环开始,在两端查找3,17之间的数字,然后取最大值并从3替换为这种情况下的最大值10。依此类推。
有没有比这更好的方法了?
答案 0 :(得分:1)
您可以执行以下操作:
def fill_gap(l, pivot='X', target='a', fill='y'):
result = l[:]
X_indices = [i for i, e in enumerate(l) if e == pivot] + [len(l)] # find the indices of pivot
for start, end in zip(X_indices, X_indices[1:]): # iterate over the slices from the indices of pivot
segment = l[start + 1:end]
try:
ye = len(segment) - 1 - segment[::-1].index(fill) # find the las appearance of fill if exists
for j, e in enumerate(segment):
if e == target and j < ye: # if equals target and if before the last appearance of fill
result[start + 1 + j] = 'y'
except ValueError:
continue
return result
lst = ['a', 'a', 'a', 'X', 'y', 'y', 'y', 'a', 'a', 'y', 'y', 'a', 'a', 'a', 'a', 'a', 'a', 'X', 'y', 'a', 'y', 'a',
'y', 'y', 'y', 'a', 'a', 'a', 'a']
print(fill_gap(lst))
print(fill_gap(['X', 'a', 'y']))
print(fill_gap(['X', 'a', 'y', 'a', 'X', 'a', 'y']))
输出
['a', 'a', 'a', 'X', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'a', 'a', 'a', 'a', 'a', 'a', 'X', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'a', 'a', 'a', 'a']
['X', 'y', 'y']
['X', 'y', 'y', 'a', 'X', 'y', 'y']
请注意,函数fill_gap
返回一个新列表(result
),但这可以很容易地更改为就地修改列表。