Home > Software engineering >  How can I split my list into a list of lists given a condition?
How can I split my list into a list of lists given a condition?

Time:05-30

Can someone help me split this list into a list of lists?

For example, given this input:

['Na', '2', ' ', 'C', ' ', 'O', '3']

I want this output:

[['Na', '2'], ['C'], ['O','3']]

CodePudding user response:

You can use itertools.groupby() to generate the desired sublists:

from itertools import groupby
[list(group) for key, group in groupby(data, key=lambda x: x == ' ') if not key]

This outputs:

[['Na', '2'], ['C'], ['O', '3']]

CodePudding user response:

lst = ['Na', '2', ' ', 'C', ' ', 'O', '3']
lst_of_lsts = []
sublist = []
for item in lst:
    if item != " ":
        sublist.append(item)
    else:
        lst_of_lsts.append(sublist)
        sublist = []
if sublist != []:
     lst_of_lsts.append(sublist)
  • Related