简体   繁体   English

如何替换列表特定元素的某些部分?

[英]How do you replace certain parts of specific elements of lists?

How would you go about replacing a part of certain items in a list?您将如何替换列表中某些项目的一部分? (Python 3.x) Say I have a list: (Python 3.x) 假设我有一个列表:

x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe", "element to save", "KeepThisPart"]

If I wanted to remove just the "removeMe" part, how would you go about it?如果我只想删除“removeMe”部分,你会怎么做? I have this so far:到目前为止我有这个:

def replaceExampleA(x, y):
    for i in x:
        if i[len(i)-8:len(i)-1] == "removeMe":
            y.append(i[0: -12])
        else:
            y.append(i)

Edit: Just realised I made a mistake - the list is more like this: x = ["part2keep removeMe 123", "saveme removeMe 12", "third length to throw it off removeMe 83", "element to save", "KeepThisPart"]编辑:刚刚意识到我犯了一个错误 - 列表更像是这样的: x = ["part2keep removeMe 123", "saveme removeMe 12", "third length to throw it off removeMe 83", "element to save", "KeepThisPart"]

I need to get rid of the numbers as well from the elements with "removeMe".我还需要使用“removeMe”从元素中删除数字。 Thanks谢谢

x = [s.replace('removeMe', '') for s in x]

This can be accomplished with list comprehension这可以通过列表理解来完成

x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe"]

print(y.replace(' removeMe', '') for y in x)

You can use regex to ensure that the code is always stripping removeMe only when it occurs at the end of the string:您可以使用正则表达式来确保代码始终仅在出现在字符串末尾时才剥离removeMe

import re
x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe", "element to save", "KeepThisPart"]
new_x = [re.sub('\sremoveMe$', '', i) for i in x]

Output:输出:

['part2keep', 'saveme', 'third length to throw it off', 'element to save', 'KeepThisPart']

You could also use the map function您还可以使用map功能

new_x = map(lambda e: e.replace('removeMe', ''), x)

The advantage of this is that you get a generator back.这样做的好处是你可以拿回发电机。 So in some situations this is more memory efficient.因此,在某些情况下,这会提高内存效率。 If you want a list back, just like the other answers, then you need to convert it back to a list如果你想要一个列表,就像其他答案一样,那么你需要将它转换回一个列表

new_x = list(new_x)

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

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