I have a list,
['t', 'p', 'k', 'F', 'p', 'l', 'v', 'F']
and I want to group the elements by the 'F', where the 'F' is the end of the group, so it splits
the list into separate groups.
Like this:
['t', 'p', 'k'] ['p', 'l', 'v']
I have a list,
['t', 'p', 'k', 'F', 'p', 'l', 'v', 'F']
and I want to group the elements by the 'F', where the 'F' is the end of the group, so it splits
the list into separate groups.
Like this:
['t', 'p', 'k'] ['p', 'l', 'v']
Use itertools.groupby()
with a key
function:
from itertools import groupby
l = ['t', 'p', 'k', 'F', 'p', 'l', 'v', 'F']
result = [list(g) for k, g in groupby(l, key=lambda x: x != 'F') if k]
>>> result
[['t', 'p', 'k'], ['p', 'l', 'v']]
Another way is with string operations:
result = [list(x) for x in ''.join(l).split('F') if x]
>>> result
[['t', 'p', 'k'], ['p', 'l', 'v']]
Note that both solutions above will include any trailing items that follow the final 'F'
. Not sure if that is what you want?
This program assumes that your list elements are always single characters. If that isn't true, you would need to work directly on the list. I convert to a string to use the convenient str.split method, then convert each substring back into a list.
inp = ['t', 'p', 'k', 'F', 'p', 'l', 'v', 'F']
print(inp)
groups_as_strings = "".join(inp).split("F")
out = [list(g) for g in groups_as_strings if g]
print(out)
This is one way.
lst = ['t', 'p', 'k', 'F', 'p', 'l', 'v', 'F']
list(map(list, ''.join(lst).split('F')[:-1]))
# [['t', 'p', 'k'], ['p', 'l', 'v']]
Simple but easy to follow solution:
new_list = []
tmp_list = []
for i in letter_list:
if i == 'F':
if tmp_list:
new_list.append(tmp_list)
tmp_list = []
continue
tmp_list.append(i)
print(new_list)
Note that this assumes empty lists (consecutive F's) should be ignored, but that's easy to remove.