替换列表中的字符串 [英] Replace a string in list of lists

查看:579
本文介绍了替换列表中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of lists of strings like:

example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]]

我想用空格替换"\r\n"(并在所有字符串的末尾删除":").

I'd like to replace the "\r\n" with a space (and strip off the ":" at the end for all the strings).

对于普通列表,我将使用列表理解来剥离或替换类似项

For a normal list I would use list comprehension to strip or replace an item like

example = [x.replace('\r\n','') for x in example]

甚至是lambda函数

or even a lambda function

map(lambda x: str.replace(x, '\r\n', ''),example)

但是我无法使其用于嵌套列表.有什么建议吗?

but I can't get it to work for a nested list. Any suggestions?

推荐答案

好吧,考虑一下原始代码在做什么:

Well, think about what your original code is doing:

example = [x.replace('\r\n','') for x in example]

您正在列表的每个元素上使用.replace()方法,就好像它是一个字符串一样.但是此列表的每个元素都是另一个列表!您不想在子级列表上调用.replace(),而是希望在其每个内容上调用它.

You're using the .replace() method on each element of the list as though it were a string. But each element of this list is another list! You don't want to call .replace() on the child list, you want to call it on each of its contents.

对于嵌套列表,请使用嵌套列表理解!

For a nested list, use nested list comprehensions!

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']]

这篇关于替换列表中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆