【问题标题】:Use "Findall" operation on Python array of strings对 Python 字符串数组使用“Findall”操作
【发布时间】:2020-08-26 03:07:07
【问题描述】:

我有一个超过 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")

【问题讨论】:

    标签: python arrays string findall


    【解决方案1】:

    不建议使用“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']
    

    【讨论】:

    • 我们快到了!感谢您创建一个函数然后循环遍历数组的想法。我觉得我只需要稍微改变一下就可以得到我需要的东西。当前输出的唯一问题是它包含额外的、不需要的字母/数字。例如,示例中数组中的最后一个输出应该只是“g2”,而不是“e4g2”。
    【解决方案2】:

    这可能不是最漂亮的方式,但我认为它可以完成工作!

    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]
    
    

    【讨论】:

      猜你喜欢
      • 2018-07-14
      • 2015-01-19
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 2011-03-22
      相关资源
      最近更新 更多