在python中拆分列表中的元素

时间:2012-05-25 13:29:13

标签: python

假设我有一个列表如:

lst = ["Line1\r\nLine2\r\n", "Line3\r\nLine4\r\n", etc.]

是否有一种漂亮的pythonic方法可以在行尾分割元素并使它们成为单独的元素,即

new_lst = ["Line1\r\n", "Line2\r\n", "Line3\r\n", "Line4\r\n"]

我知道我可以有一些额外的代码行来循环遍历列表,拆分元素并将它们存储在一个新的列表中,但我对python相对较新,并且想养成使用习惯所有很酷的功能,如列表理解。提前谢谢!

4 个答案:

答案 0 :(得分:10)

>>> lst = ["Line1\r\nLine2\r\n", "Line3\r\nLine4\r\n"]
>>> new_lst = [elem for l in lst for elem in l.splitlines(True)]
>>> new_lst
['Line1\r\n', 'Line2\r\n', 'Line3\r\n', 'Line4\r\n']

答案 1 :(得分:6)

import itertools as it
list(it.chain(*(elem.splitlines(True) for elem in lst)))

[line for elem in lst for line in elem.splitlines(True)]

都返回:['Line1\r\n', 'Line2\r\n', 'Line3\r\n', 'Line4\r\n']

来自doc:

S.splitlines([keepends]) -> list of strings

Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.

这适用于\r\n以及\r\n

答案 2 :(得分:0)

new_lst = [x + '\r\n' for x in ''.join(lst).split('\r\n')][:-1]

答案 3 :(得分:0)

为了完整性,让我们添加这个丑陋的解决方案;)

new_lst = ('\r\n'.join(lst)).splitlines(True)