python - 替换列表列表中的字符串

标签 python list python-3.x replace nested-lists

我有一个字符串列表列表,例如:

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/

相关文章:

python - 使用其他列中的一些值创建列 - 有条件

python - Django : Page not found (404) Why. ..?

python - 无法使用请求从网页获取所有表格内容

python - 如何在python脚本中提升到root权限?

python - Cx-卡住错误 - Python 34

python - IDLE (Python 3.4) - 在启动时执行脚本

python - logging.config,属性错误 : type object 'FileHandler' has no attribute 'split'

Java:最好将实体中的列表初始化为空列表或空列表

java - 元素不会从列表中删除

python - 如何在 Python 的列表中获取字符串的位置?