替换列表列表中的字符串

问题描述 投票:0回答:7

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

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)

但我无法让它为嵌套列表工作。有什么建议吗?

python list python-3.x replace nested-lists
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']]

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

3
投票

如果您的列表比您举的例子更复杂,例如,如果它们有三层嵌套,则以下内容将遍历列表及其所有子列表,替换 在遇到的任何字符串中都有空格。

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
投票

适合初学者!

把你好变成“再见”。

第一步:先索引

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

然后您将进入第二个列表,其中它从零开始。该列表作为一个整体是索引 2,所以当引用索引 2 时,它意味着你在 [3,4,'hello']

第 2 步找出你好索引

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

因为你再次从 0 开始,所以你从 0 开始,直到你得到你想要改变的数字或字符串。你也可以做 -1 因为 hello 是列表的最后一个索引

list3[2][2] = 'goodbye'

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

我希望这能解决问题!

© www.soinside.com 2019 - 2024. All rights reserved.