简体   繁体   中英

How can I split my list into a list of lists given a condition?

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']]

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']]
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM