【问题标题】:Find matching substrings in two lists在两个列表中查找匹配的子字符串
【发布时间】:2018-12-07 16:07:06
【问题描述】:

我有两个列表:A 和 B。列表长度不同,它们都包含字符串。匹配两个列表中的子字符串的最佳方法是什么?

list_A = ['hello','there','you','are']
list_B = ['say_hellaa','therefore','foursquare']

我想要一个名为 list_C 的匹配子字符串列表,其中包含:

list_C = ['hell','there','are']

我遇到了this 的答案,但它要求我有一个匹配子字符串的列表。 有没有一种方法可以在不手动创建匹配子字符串列表的情况下得到我想要的?

This 也无济于事,因为第二个列表包含子字符串。

【问题讨论】:

  • Also suggest ways to implement 可能不是故意的,但是当你这样写时,它会显得很粗鲁,让人不太愿意提供帮助。
  • 最高效的解决方案很大程度上取决于两个列表相互关联的时间以及字符串和模式的平均长度。
  • @SuperStew 道歉,无意。将其编辑出来。
  • 5 分钟前询问了一个副本!
  • @schwobaseggl 我实际上有一个大约 500,000 行的 pandas 列,列中大约有 100 个唯一字符串。

标签: python string pandas


【解决方案1】:

为了有趣,这里有一个使用正则表达式的答案!

import re

matches = []
for pat in list_B:
    matches.append(re.search(pat, ' '.join(list_A)))
matches = [mat.group() for mat in matches if mat]
print(matches)
# ['hell', 'here']

这将为找到的每个匹配项返回一个匹配对象,其实际字符串由match.group() 找到。请注意,如果没有找到匹配项(就像您的 list_B 中的第二个元素一样),您会在 matches 中获得一个 None,因此需要在列表理解的末尾添加 if mat .

【讨论】:

    【解决方案2】:

    IIUC:我会使用 Numpy

    import numpy as np
    from numpy.core.defchararray import find
    
    a = np.array(['hello', 'there', 'you', 'are', 'up', 'date'])
    b = np.array(['hell', 'is', 'here', 'update'])
    
    bina = b[np.where(find(a[:, None], b) > -1)[1]]
    ainb = a[np.where(find(b, a[:, None]) > -1)[0]]
    
    np.append(bina, ainb)
    
    array(['hell', 'here', 'up', 'date'], dtype='<U6')
    

    【讨论】:

    • 任何原因your answer here 不起作用? (如果您认为这个问题存在重大差异,请随时重新打开。)
    • 是的,除非我误解了。 OP想要一个双向检查。否则,我将删除。其实我也没有做对。修复。
    【解决方案3】:
    list_A = ['hello','there','you','are']
    list_B = ['hell','is','here']
    List_C = []
    
    for a in list_A:
        for b in list_B:
            print(a,"<->",b)
            if a in b:
                List_C.append(a)
            if b in a:
                List_C.append(b)
    
    print(List_C)
    

    【讨论】:

    • 请不要在您的帖子中使用攻击性语言。谢谢。
    【解决方案4】:

    由于您从str.contains 标记pandas 解决方案

    #S_A=pd.Series(list_A)
    #S_B=pd.Series(list_B)
    
    S_B[S_B.apply(lambda x : S_A.str.contains(x)).any(1)]
    Out[441]: 
    0    hell
    2    here
    dtype: object
    

    【讨论】:

      【解决方案5】:

      这是一种方法。使用list comprehension

      list_A = ['hello','there','you','are']
      list_B = ['hell','is','here']
      jVal = "|".join(list_A)        # hello|there|you|are
      
      print([i for i in list_B if i in jVal ])
      

      输出:

      ['hell', 'here']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-11
        • 2019-07-10
        • 2017-10-21
        • 1970-01-01
        • 2019-11-27
        • 1970-01-01
        相关资源
        最近更新 更多