So I want to loop through a list starting at string "B" to the end or until a new "B" is reached and so on till the end of the list.
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)
I want to loop through the list so I get these outputs but without hard coding the indices:
l[1:4]=['B', 'C', 'D']
l[4:8]=['B', 'M', 'C', 'T']
l[8:]=['B', 'g', 'do']
If just one index has that string then
l=["A", "B", "C", "D"]
index = [idx for idx, s in enumerate(l) if 'B' in s]
print(index)
l[1:]=["B", "C", "D"]
CodePudding user response:
Try this:
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))
Output:
[['B', 'C', 'D'], ['B', 'M', 'C', 'T'], ['B', 'g', 'do']]
CodePudding user response:
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]
CodePudding user response:
Taking your code and using a 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)
Or a list comprehension:
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)
Output:
[['B', 'C', 'D'], ['B', 'M', 'C', 'T'], ['B', 'g', 'do']]