简体   繁体   English

如何在给定条件的情况下将我的列表拆分为列表列表?

[英]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:您可以使用itertools.groupby()生成所需的子列表:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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