Python比较无序列表,其中一个列表中的元素具有前缀文本

2024-06-16 11:24:31 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python中对两个列表进行比较,以找到列表a中的项目,这些项目不也出现在列表B中,但每个列表中的项目的格式/布局略有不同,其中一个列表的每个项目上都有前缀/词缀

我认为这将是一个简单的[List a-List B],但这似乎是在搜索文本1对1的匹配,在这种情况下,逻辑意味着List a中没有任何项与List B中的项匹配

例如: 列表A中的项目带有文本前缀:

[ 'foo/BAR', 'foo/XYZ', 'foo/ABC', 'foo/123' ]

和列表B,其中项目不包括前缀:

[ 'ABC', 'ZYX', '123', 'BAR' ]

这样做的方法是在进行任何比较之前格式化列表A并删除前缀吗? 或者有没有一种不需要格式化就可以比较项目的方法


Tags: 项目方法文本列表foo格式bar情况
3条回答

看起来你想要['foo/XYZ']。您可以迭代A,在斜杠上拆分,然后检查第二部分是否在B中

a = ['foo/BAR', 'foo/XYZ', 'foo/ABC', 'foo/123']
b = ['ABC', 'ZYX', '123', 'BAR']

out = []
for s in a:
    prefix, word = s.split('/')
    if word not in b:
        out.append(s)
print(out)  # -> ['foo/XYZ']

或作为列表:

out = [s for s in a if s.split('/')[1] not in b]
print(out)  # -> ['foo/XYZ']

我想这就是你要找的

set_a = [ 'foo/BAR', 'foo/XYZ', 'foo/ABC', 'foo/123' ]

set_b = [ 'ABC', 'ZYX', '123', 'BAR' ]

def parse_from_a(x):
    if '/' in x:
        return x.split('/')[1]
    # add more parsing logic here
    return x

fixed_set_a = {parse_from_a(x) for x in set_a}
fixed_set_b = set(set_b)

print(fixed_set_a - fixed_set_b)

它打印单个项目集:

{'XYZ'}

set_a = {'foo/BAR', 'foo/XYZ', 'foo/ABC', 'foo/123'}
set_b = {'ABC', 'ZYX', '123', 'BAR'}

final_set_a = {item for x in set_a for item in set_b if x in item}
final_set_b = {item for x in set_b for item in set_a if x in item}

if final_set_b:
    print(set_a ^ final_set_b)
elif final_set_a:
    print(set_b ^ final_set_a)

相关问题 更多 >