我有一个字符串列表列表,例如:
example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]]
我想用空格替换 "\r\n"
(并在所有字符串的末尾去掉 ":"
)。
对于普通列表,我会使用列表理解来删除或替换一个项目,例如
example = [x.replace('\r\n','') for x in example]
甚至是 lambda 函数
map(lambda x: str.replace(x, '\r\n', ''),example)
但我无法让它为嵌套列表工作。有什么建议吗?
最佳答案
好吧,想想你的原始代码在做什么:
example = [x.replace('\r\n','') for x in example]
您正在对列表的每个元素使用 .replace()
方法,就好像它是一个字符串一样。但是这个列表的每个元素都是另一个列表!你不想在子列表上调用 .replace()
,你想在它的每个内容上调用它。
对于嵌套列表,使用嵌套列表理解!
example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]]
example = [[x.replace('\r\n','') for x in l] for l in example]
print example
[['string 1', 'atest string:'], ['string 1', 'test 2: anothertest string']]
关于python - 替换列表列表中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13781828/