【问题标题】:Find exact match in list of strings在字符串列表中查找完全匹配
【发布时间】:2016-02-12 04:48:46
【问题描述】:

对此非常陌生,请多多包涵……

我有一个预定义的单词列表

checklist = ['A','FOO']

还有来自line.split() 的单词列表,看起来像这样

words = ['fAr', 'near', 'A']

我需要words中的checklist完全匹配,所以我只找到'A':

if checklist[0] in words:

这不起作用,所以我尝试了一些在这里找到的建议:

if re.search(r'\b'checklist[0]'\b', line): 

无济于事,因为我显然无法寻找这样的列表对象...对此有什么帮助吗?

【问题讨论】:

  • 当您可以遍历数组并检查元素是否在预定义数组中时,这里的正则表达式是多余的。
  • checklist[0] in words。您能否更具体地说明它是如何“不起作用”的?
  • 那你想做什么? 在字符串列表中查找完全匹配是什么意思?
  • 抱歉表述不准确,下次会更清楚地表述。压力。干杯。

标签: python regex string string-matching


【解决方案1】:

使用集合比遍历列表要快得多。

checklist = ['A', 'FOO']
words = ['fAr', 'near', 'A']
matches = set(checklist).intersection(set(words))
print(matches)  # {'A'}

【讨论】:

    【解决方案2】:

    这将为您提供完全匹配的列表。

    matches = [c for c in checklist if c in words]

    等同于:

    matches = []
    for c in checklist:
      if c in words:
        matches.append(c)
    

    【讨论】:

      【解决方案3】:

      Set 将满足您的需求。有一个issubset 设置方法。示例如下:

      checklist = ['A','FOO']
      words = ['fAr', 'near', 'A']
      
      print set(checklist).issubset(set(words))
      

      如果您只需要测试两个列表中是否有评论元素,您可以更改为intersection方法。

      【讨论】:

      • set 方法非常好用,如果您有大型数据集,它们比使用 for 循环要快得多。
      • 此方法无效。当我应该得到“真”时,我得到“假”。
      【解决方案4】:

      让我知道这是否适合你,

      In [67]: test = re.match(r"(.*?)A(.*?)$", "CAT")
      

      在 [68] 中:test.group(2)

      输出[68]:'T'

      在 [69] 中:test.group()

      输出[69]:'猫'

      在 [70] 中:test.group(1)

      输出[70]:'C'

      如果模式不匹配,则测试对象不存在。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-04
        • 1970-01-01
        • 1970-01-01
        • 2013-05-21
        • 1970-01-01
        相关资源
        最近更新 更多