python - 如何在基于字符分隔符将列表拆分为子列表时跳过空子字符串

标签 python python-3.x string list split

我有以下列表

list_big = ['90', '=', 'C', '44', '=']

我想要的输出是连接 '=' 之间的所有字符串,如下所示:

list_smaller = ['90', 'C44']

我跑:

list_smaller = [l.split(',') for l in ','.join(list_big).split('=')]

但我得到:

list_smaller = [['90', ''], ['', 'C', '44', ''], ['']]

如何获得所需的输出?

最佳答案

您可以使用以下列表理解;使用空字符串而不是逗号进行连接,然后使用 if l 仅将非空字符串的元素放入列表中。

>>> [l for l in ''.join(list_big).split('=') if l]
['90', 'C44']

关于python - 如何在基于字符分隔符将列表拆分为子列表时跳过空子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60037954/

相关文章:

python - 如何处理python 3中的错误 "too many arguments"

string - "Simple String template replacement in Scala and Clojure"的后续

C 将字符串插入字符指针

python - Object.keys() 的 Python 版本是什么?

python - 调用 PyArray_DATA 后 DECREF'ing

python - scapy 中未定义名称 'raw'

python - 在 python 中离线绘制世界 Choropleth map ?

python - s.find() 和 s.index() 之间哪个更快

python - Python中是否有文字字符串

c# - 使用 InvariantCultureIgnoreCase 而不是 ToUpper 进行不区分大小写的字符串比较