How to split a list to list of lists based on empty strings in Python

2 Answers

0 votes
from itertools import groupby 

lst = ['java', '', 'python', 'php', '', 'c', 'c++', 'c#', '', 'javascript'] 

lst = [list(sub) for e, sub in groupby(lst, key = bool) if e] 
  
print(lst) 
     


        
'''
run:
 
[['java'], ['python', 'php'], ['c', 'c++', 'c#'], ['javascript']]
        
'''

 



answered May 2, 2020 by avibootz
0 votes
lst = ['java', '', 'python', 'php', '', 'c', 'c++', 'c#', '', 'javascript'] 

result = [[]]
for s in lst:
    if not s:
        result.append([])
    else:
        result[-1].append(s)

print(result)
    


        
'''
run:
 
[['java'], ['python', 'php'], ['c', 'c++', 'c#'], ['javascript']]
        
'''

 



answered May 2, 2020 by avibootz
...