按空元素拆分列表 [英] Splitting lists by empty element

查看:72
本文介绍了按空元素拆分列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以包含任意数量元素的列表.

I have a single list that could be any amount of elements.

['jeff','ham','boat','','my','name','hello']

如何根据空白字符串元素将一个列表分为两个列表或任意数量的列表?

How do I split this one list into two lists or any amount of lists depending on blank string elements?

然后将所有这些列表放入一个列表列表中.

All these lists can then be put into one list of lists.

推荐答案

这是使用简单迭代的一种方法.

This is one approach using a simple iteration.

例如:

myList = ['jeff','ham','boat','','my','name','hello']
result = [[]]
for i in myList:
    if not i:
        result.append([])
    else:
        result[-1].append(i)
print(result)

输出:

[['jeff', 'ham', 'boat'], ['my', 'name', 'hello']]

这篇关于按空元素拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆