Replace a string in list of lists

谁说我不能喝 提交于 2019-12-05 20:33:33

问题


I have a list of lists of strings like:

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).

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]

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?


回答1:


Well, think about what your original code is doing:

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.

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



回答2:


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



回答3:


In case your lists get more complicated than the one you gave as an example, for instance if they had three layers of nesting, the following would go through the list and all its sub-lists replacing the \r\n with space in any string it comes across.

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)



回答4:


The following example, iterate between lists of lists (sublists), in order to replace a string, a word.

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


来源:https://stackoverflow.com/questions/13781828/replace-a-string-in-list-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!