【问题标题】:find all items in list with partial content matches查找列表中具有部分内容匹配的所有项目
【发布时间】:2019-08-07 02:08:12
【问题描述】:

如果项目包含与列表中其他项目相同的字符串,我正在尝试匹配列表中的项目。

所以我有一个列表,如果有一个“。”,我只会检查列表中的项目。目前在其中。

for g in groups:
    if '.' in g:
        print(g)

663.ord1,664.ord1
947.dfw3,949.dfw3
663.ord1
665.ord1,664.ord1
663.ord1,665.ord1
949.dfw3,948.dfw3
949.dfw3
947.dfw3,948.dfw3

如果项目的第一部分与项目的另一个第一部分相匹配,我想要做的是打印一个 2 项目列表(在 '.' 上分隔)

所以对于上面列出的输入。我正在寻找以下内容,不一定按此顺序:

['663.ord1,664.ord1', '663.ord1']
['947.dfw3,949.dfw3','949.dfw3,948.dfw3']
['947.dfw3,949.dfw3','949.dfw3']
['947.dfw3,949.dfw3','947.dfw3,948.dfw3']
['665.ord1,664.ord1','663.ord1,665.ord1']
['663.ord1,665.ord1','663.ord1']
['949.dfw3,948.dfw3','947.dfw3,948.dfw3']

...我想我都知道了...

有人知道如何做到这一点吗?

【问题讨论】:

  • 为什么 "663.ord1,664.ord1" 不匹配 "665.ord1,664.ord1" ?我不确定你的输出:/

标签: python list


【解决方案1】:

这可以通过正则表达式来完成。例如,您可以使用类似于pattern.search('.').span 和子字符串的内容来拆分字符串,然后进行比较。 我不太清楚您实际上希望列表基于哪些标准,但我会做一些事情来让您的示例展示它是如何工作的。 在实际代码中,它看起来像这样:

import re

def match_parts():
    # The list that's going to contain our results
    result = list()
    # assign the pattern we're going to match.
    pattern = re.compile('\.[a-z]*,')
    for g in groups:
        m = pattern.search(g)
        sp = m.span()
        str = g[sp[1]:sp[2]]    # Get a substring containing data we want compared
        for h in groups:
            m2 = pattern.search(h)
            sp2 = m2.span()
            str2 = h[sp2[1]:sp2[2]]
            if (str == str2):
                results.append([g,h])

    for i in results:
            print(i)

这应该有点你想要的。由于在发现它匹配后没有从列表中删除该项目,可能会有一些冗余,但除此之外它应该是好的。如果我犯了错误,请发表评论,我会纠正它。

【讨论】:

    【解决方案2】:

    这是一个可能的解决方案:

    groups = ['663.ord1,664.ord1', '947.dfw3,949.dfw3', '663.ord1', '665.ord1,664.ord1', '663.ord1,665.ord1', '949.dfw3,948.dfw3', '949.dfw3', '947.dfw3,948.dfw3', 'plus other stuff']
    
    # use a list comprehension to get items that have '.'
    g1 = [g for g in groups if '.' in g]
    g2 = g1
    # use 'set' to get unique combinations
    # use split(',')[0] to get the first element in e1
    # check whether that split element is in e2
    # check that elements in each tuple are not identical, i.e. e1 not equal to e2
    s = set((e1,e2) for e1 in g1 for e2 in g2 if e1.split(',')[0] in e2 and e1 != e2)
    
    # You would also want to get rid of reverse duplicates:
    # For explanation see accepted answer at: https://stackoverflow.com/questions/41164630/pythonic-way-of-removing-reversed-duplicates-in-list/41173005#41173005
    s2 = {tuple(sorted([e1,e2])) for (e1,e2) in s}
    
    # Then you can print out the lists
    for (e1,e2) in s2:
        print([e1,e2])
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多