0

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']
Nikunj
  • 3,937
  • 19
  • 33
Seminem
  • 11
  • 1
  • 2
    Possible duplicate of [Python spliting a list based on a delimiter word](https://stackoverflow.com/questions/15357830/python-spliting-a-list-based-on-a-delimiter-word) – quamrana Jan 30 '18 at 09:14

4 Answers4

1

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?

mhawke
  • 84,695
  • 9
  • 117
  • 138
1

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)
John Ladasky
  • 1,016
  • 8
  • 17
0

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']]
jpp
  • 159,742
  • 34
  • 281
  • 339
0

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.

match
  • 10,388
  • 3
  • 23
  • 41