1

假设我有一个列表,例如:

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

4 回答 4

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']
于 2012-05-25T13:35:25.107 回答
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']

来自文档:

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

于 2012-05-25T13:33:50.620 回答
0
new_lst = [x + '\r\n' for x in ''.join(lst).split('\r\n')][:-1]
于 2012-05-25T13:34:19.513 回答
0

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

new_lst = ('\r\n'.join(lst)).splitlines(True)
于 2012-05-25T14:15:35.687 回答