简体   繁体   English

Python,如何替换列表中元素的多个部分(列表中)

[英]Python, How to replace multiple parts (in a list) of elements in a list

A list of original strings: 原始字符串列表:

Originals = ["nice apple", "orange", "pear sweet", "red ape"]

A list of strings to remove: 要删除的字符串列表:

To_remove = ["nice ", " sweet"]

What I want to achieve is to remove the strings needed to be removed in each elements in the original words 我要实现的是删除原始单词中每个元素中需要删除的字符串

result: ["apple", "orange", "pear", "red ape"]

I do following but it doesn't produce a good result. 我会关注,但效果不佳。

for t in To_remove:
    for o in Originals:
        print o.replace(t, "")

what would be the right way? 正确的方法是什么? Thank you. 谢谢。

Because string is immutable, you have to reassign the list element. 由于字符串是不可变的,因此您必须重新分配列表元素。

for t in To_remove:
    for i, o in enumerate(Originals):
        Originals[i] = o.replace(t, "")

print Originals 

hope this helps. 希望这可以帮助。

Strings are immutable. 字符串是不可变的。 Hence, none of the methods you can call on a string does an in-place modification. 因此,您不能在字符串上调用的任何方法都进行就地修改。 They all return a new string, so you have to reassign the string returned by replace : 它们都返回一个新字符串,因此您必须重新分配由replace返回的字符串:

for t in To_remove:
    for i in range(len(Originals)):
        Originals[i] = Originals[i].replace(t, "")

You can check out this question for how to merge the replacement of multiple patterns. 您可以查看此问题以了解如何合并多个模式的替换。

You are printing the results of the replacement, but do not change the list contents. 您正在打印替换的结果,但不要更改列表内容。 If you have a closer look on the replace method (for string s(!)), you'll see that you are not only not changing the list but also not changing the strings you are getting for o in Originals . 如果您仔细查看replace方法 (用于字符串 s(!)),您会发现不仅在更改列表,而且还没有更改for o in Originals中获取for o in Originals的字符串。 I omit including a working example, since schwobaseggl and thangtn [1] already provide it. 我省略了一个工作示例,因为schwobasegglthangtn [1]已经提供了它。


[1] Who was really first? [1]谁是第一位? The SO timestamps contradict my personal experience. SO时间戳与我的个人经历相矛盾。

Originals = ["nice apple", "orange", "pear sweet", "red ape"]
To_remove = ["nice ", " sweet"]
result = []

for o in Originals:
    for t in To_remove:
        result.append(o.replace(t, ""))

print result

Is that what you need? 那是你需要的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM