[英]How do you replace certain parts of specific elements of lists?
您將如何替換列表中某些項目的一部分? (Python 3.x) 假設我有一個列表:
x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe", "element to save", "KeepThisPart"]
如果我只想刪除“removeMe”部分,你會怎么做? 到目前為止我有這個:
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)
編輯:剛剛意識到我犯了一個錯誤 - 列表更像是這樣的: x = ["part2keep removeMe 123", "saveme removeMe 12", "third length to throw it off removeMe 83", "element to save", "KeepThisPart"]
我還需要使用“removeMe”從元素中刪除數字。 謝謝
x = [s.replace('removeMe', '') for s in x]
這可以通過列表理解來完成
x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe"]
print(y.replace(' removeMe', '') for y in x)
您可以使用正則表達式來確保代碼始終僅在出現在字符串末尾時才剝離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]
輸出:
['part2keep', 'saveme', 'third length to throw it off', 'element to save', 'KeepThisPart']
您還可以使用map
功能
new_x = map(lambda e: e.replace('removeMe', ''), x)
這樣做的好處是你可以拿回發電機。 因此,在某些情況下,這會提高內存效率。 如果你想要一個列表,就像其他答案一樣,那么你需要將它轉換回一個列表
new_x = list(new_x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.