Python:在特定索引处循环遍历列表(包含特定字符串)



我想循环遍历一个从string "B"直到最后或直到一个新的";B";,依此类推,直到列表末尾。

l=["A", "B", "C", "D", "B", "M", "C", "T", "B", "g", "do"]
index = [idx for idx, s in enumerate(l) if 'B' in s]
print(index)

我想循环遍历列表,这样我就可以得到这些输出,但不需要对索引进行硬编码:

l[1:4]=['B', 'C', 'D']
l[4:8]=['B', 'M', 'C', 'T']
l[8:]=['B', 'g', 'do']

如果只有一个索引有这个字符串,那么

l=["A", "B", "C", "D"]
index = [idx for idx, s in enumerate(l) if 'B' in s]
print(index)
l[1:]=["B", "C", "D"]

使用for loop:

l = ["A", "B", "C", "D", "B", "M", "C", "T", "B", "g", "do"]
index = [idx for idx, s in enumerate(l) if 'B' in s]
out_of_bounds_index = len(index)
result = []
for i in range(out_of_bounds_index):
if i+1 < out_of_bounds_index:
result.append(l[index[i]:index[i+1]])
else:
result.append(l[index[i]:])

print(result)

或列表推导式:

l = ["A", "B", "C", "D", "B", "M", "C", "T", "B", "g", "do"]
index = [idx for idx, s in enumerate(l) if 'B' in s]
out_of_bounds_index = len(index)
result = [l[index[i]:index[i+1]] 
if i+1 < out_of_bounds_index 
else l[index[i]:] 
for i in range(out_of_bounds_index)]

print(result)

输出:

[['B', 'C', 'D'], ['B', 'M', 'C', 'T'], ['B', 'g', 'do']]

试试这个:

def get_lists(l):
indices = [i for i, x in enumerate(l) if x == "B"]
if len(indices) == 0:
return []
elif len(indices) == 1:
return [[l[indices[0]]]]
else:
result = list()
for i in range(len(indices)):
if indices[i] == indices[-1]:
result.append(l[indices[i]:])
else:
result.append(l[indices[i]:indices[i+1]])

return result

k = ["A", "B", "C", "D", "B", "M", "C", "T", "B", "g", "do"]
print(get_lists(k))

输出:

[['B', 'C', 'D'], ['B', 'M', 'C', 'T'], ['B', 'g', 'do']]
l = ["A", "B", "C", "D", "B", "M", "C", "T", "B", "g", "do"]
#note that an extra 'B' is added to the list: l+['B']
indexOfB = [i for i, x in enumerate(l+['B']) if x == 'B']
Blists = [l[i[0]:i[1]] for i in zip(indexOfB, indexOfB[1:])]
[print(x) for x in Blists]

相关内容

  • 没有找到相关文章