我有一個很長的串列,其中包含很多存在 2 個“值”的子串列,例如
test=[["AAAGG1","AAAAA22"],["GGGGA1","AAGGA"],["GGGGG23","GGAGA6"]]
我想要的是替換或洗掉最后一位數字。因此我嘗試使用一個很長的函式:
def remove_numbers(index,newlist):
for com in index:
for dup in com:
if "1" in dup:
newlist.append(dup.replace("1",""))
elif "2" in dup:
newlist.append(dup.replace("2",""))
elif "3" in dup:
newlist.append(dup.replace("3",""))
elif "4" in dup:
newlist.append(dup.replace("4",""))
elif "5" in dup:
newlist.append(dup.replace("5",""))
elif "6" in dup:
newlist.append(dup.replace("6",""))
elif "7" in dup:
newlist.append(dup.replace("7",""))
elif "8" in dup:
newlist.append(dup.replace("8",""))
elif "9" in dup:
newlist.append(dup.replace("9",""))
else:
newlist.append(dup)
我創建了一個空串列并呼叫了函式
emptytest=[]
testfunction=remove_numbers(test,emptytest)
當我呼叫空測驗時,我的輸出如下
['AAAGG', 'AAAAA', 'GGGGA', 'AAGGA', 'GGGGG3', 'GGAGA']
問題是它現在是一個串列,當最后有兩個不同的數字時,它們不會全部被洗掉/替換。我需要子串列保持不變。
有人知道解決方案嗎?
抱歉,如果這是一個簡單的問題,因為我對 python 還沒有那么豐富的經驗,但是我在網路或現有論壇上找不到合適的解決方案。
uj5u.com熱心網友回復:
您需要的是使用正則運算式來替換數字,而不是手動識別所有內容。整個事情可以通過下面的2行來實作。
import re
processed = [[re.sub(r"\d $","",n) for n in t] for t in test]
print(processed)
給出一個結果
[['AAAGG', 'AAAAA'], ['GGGGA', 'AAGGA'], ['GGGGG', 'GGAGA']]
在這里,我們使用了一個正則運算式"\d $",它基本上匹配字串末尾的數字模式。如果識別出這樣的模式,那么我們將其替換為空。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/436044.html
標籤:python-3.x 列表 功能 代替 子列表
