[英]Use “Findall” operation on Python array of strings
我有一個 1m+ 行的數據集,每一行都有小寫/大寫字母、符號和數字的組合。 我希望清理這些數據,只保留小寫字母和數字並排的最后一個實例。 為了提高速度效率,我目前的計划是將這些數據作為一個字符串數組,然后使用 .findall 操作來保留我正在尋找的字母/數字組合。
這是我正在嘗試做的事情:
輸入
list = Array(["Nd4","0-0","Nxe4","e8+","e4g2"])
newList = list.findall('[a-z]\d')[len(list.findall('[a-z]\d')-1]
newList 的預期輸出
newList = ("d4","","e4","e8","g2")
不建議使用“list”來分配變量,因為它是一個內置函數
import re
import numpy as np
lists = np.array(["Nd4","0-0","Nxe4","e8+","e4g2"])
def findall(i,pattern=r'[a-z1-9]+'):
return re.findall(pattern,i)[0] if re.findall(pattern,i) else ""
newList = [findall(i) for i in lists]
# OR if you want to return an array
newList = np.array(list(map(findall,lists)))
# >>> ['d4', '', 'xe4', 'e8', 'e4g2']
這可能不是最漂亮的方式,但我認為它可以完成工作!
import re
import numpy as np
lists = np.array(["Nd4","0-0","Nxe4","e8+","e4g2"])
def function(i):
try:
return re.findall(r'[a-z]\d',i)[len(re.findall(r'[a-z]\d',i))-1]
except:
return ""
newList = [function(i) for i in lists]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.