在列表的列表中替换一个字符串

9

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

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)

但我无法使其适用于嵌套列表。有什么建议吗?
7个回答

18

好的,请考虑一下你原来的代码在做什么:

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,但是找不到一个好的例子。我设法让它在我的程序中工作了。我发现我试图调用两次示例,如:for x in example] for l in example] - user1888390
如果我不知道列表嵌套的深度,但是想要在整个列表中进行替换,该怎么办? - Peter.k

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

2
能够解释一下正在发生的事情会很好。 - Joseph at SwiftOtter

3

如果您的列表比您提供的示例更复杂,例如如果它们有三层嵌套,以下内容将通过列表及其所有子列表,用空格替换所有字符串中的\r\n。

def replace_chars(s):
    return s.replace('\r\n', ' ')

def recursive_map(function, arg):
    return [(recursive_map(function, item) if type(item) is list else function(item))
            for item in arg]

example = [[["dsfasdf", "another\r\ntest extra embedded"], 
         "ans a \r\n string here"],
        ['another \r\nlist'], "and \r\n another string"]
print recursive_map(replace_chars, example)

1
以下示例中,迭代列表的列表(子列表),以替换字符串或单词。
myoldlist=[['aa bbbbb'],['dd myword'],['aa myword']]
mynewlist=[]
for i in xrange(0,3,1):
    mynewlist.append([x.replace('myword', 'new_word') for x in myoldlist[i]])

print mynewlist
# ['aa bbbbb'],['dd new_word'],['aa new_word']

0

你可以通过以下代码轻松实现

example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]]
example_replaced = []
def replace(n):
    new = n.replace("\r\n" , " ")
    if new[:-1] == ":" : new = new[:-1]
    return new

for item in example:
    Replaced = [replace(sub_item) for sub_item in item]
    example_replaced.append(Replaced)
print(example_replaced)

输出结果将为:

[['string 1', 'a test string:'], ['string 1', 'test 2: another test string']]

享受吧 :)


0

这是一个使用递归和生成器的实现

def replace_nested(lst, old_str, new_str):
    for item in lst:
        if isinstance(item, list):
            yield list(replace_nested(item, old_str, new_str))
        else:
            yield item.replace(old_str, new_str).rstrip(':')

example = [
    ["string 1", "a\r\ntest string:"],
    ["string 1", "test 2: another\r\ntest string"]
]
new_example = list(replace_nested(example, '\r\n', ' '))
print(new_example)

输出

[['string 1', 'a test string'], ['string 1', 'test 2: another test string']]

-1

适合初学者!

把“hello”改为“goodbye”。

步骤1:首先索引。

list3 = [1,2,[3,4,'hello']]
   index=0 1      2

然后你进入第二个列表,它从零开始。整个列表的索引为2,因此当引用索引2时,它意味着你在[3,4,“hello”]处。

步骤2找出“hello”的索引。

list3 = [1,2,[3,4,'hello']]
       index= 0 1    2

由于您重新从0开始,因此您需要从0开始直到获得要更改的数字或字符串。您也可以使用-1,因为“hello”是列表的最后一个索引。

list3[2][2] = 'goodbye'

结果 = [1,2,[3,4,'再见']]

希望这样能解决问题!


目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接