0

Could somebody help me to split a list into a list of lists by element ('#')?

Input:

['1', '2','#','3','4','#','5']

Output:

[['1', '2'], ['3','4'], ['5']]
Greenonline
  • 1,330
  • 8
  • 23
  • 31

3 Answers3

2
input = ['1', '2','#','3','4','#','5']
s = ''.join(input).split('#')
r = []
for i in s:
    r.append(list(i))
output = r
ljk321
  • 16,242
  • 7
  • 48
  • 60
  • Can you add some explanation to your answer? – Alex Char Jan 19 '15 at 08:58
  • @AlexChar This is basically the same as zoosuck's answer above. First combine all the character in the list into a string, then split it using '#' as seperator. Now the list is ['12', '34', '5']. Then split all the strings back to list. – ljk321 Jan 19 '15 at 10:53
2

Use string join and split method:

alist=  ['1', '2','#','3','4','#','5']
as_string = ' '.join(alist).split('#')
as_string_list = [i.strip().split(' ') for i in as_string]
print as_string_list
lqhcpsgbl
  • 3,694
  • 3
  • 21
  • 30
1

Here is your answer:

[list(x[1]) for x in itertools.groupby(myList, lambda x: x=='#') if not x[0]] 

This question is a duplicate of Make Python Sublists from a list using a Separator. That is were the modified answer comes from.

Community
  • 1
  • 1
Greenonline
  • 1,330
  • 8
  • 23
  • 31