替换列表中的字符串

我有一个类似的字符串列表:

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

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

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

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 i] for i in example]
点赞
评论
回不去旳甜
回不去旳甜

下面的示例在列表(子列表)列表之间进行迭代,以替换字符串,单词。

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']
点赞
评论
燕晓彤
燕晓彤

如果您的列表比示例中的列表复杂,例如,如果它们具有三层嵌套,则以下内容将遍历该列表及其所有子列表,用任何字符串中的空格替换\ r \ n它碰到了。

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

def recursively_apply(l, f):
    for n, i in enumerate(l):
        if type(i) is list:
            l[n] = recursively_apply(l[n], f)
        elif type(i) is str:
            l[n] = f(i)
    return l
example = [[["dsfasdf", "another\r\ntest extra embedded"], 
         "ans a \r\n string here"],
        ['another \r\nlist'], "and \r\n another string"]
print recursively_apply(example, replace_chars)
点赞
评论
det
det

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

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

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.

对于嵌套列表,请使用嵌套列表推导!

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']]
点赞
评论