比较结尾有特殊字符的字符串

2024-06-06 13:21:38 发布

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

我有两套

a[i]={'aaa@','bb','ccc@'}
b[j]={'aaa','bb@','ccc@'}

我想将a[i]中的每个字符串与b[j]进行比较,这样如果两个字符串都是相同的,并且它们的末尾都有特殊字符,那么它会像ccc@一样打印“相等”。在上面的列表中,如果字符串是相等的,但是其中一个有特殊字符,那么它会显示“不完全匹配”


Tags: 字符串列表ccc末尾bbaaa特殊字符
2条回答

列表示例:

a=['aaa@','bb','ccc@']
b=['aaa','bb@','ccc@']

index = 0
print "ordered comparison:"
for i,j in zip(a,b):
    if i == j:
        print str(index) + ": Equal"
    elif i.replace("@","") == j.replace("@",""):
        print str(index) + ": Not completely Matched"
    else:
        print str(index) + ": Different"
    index+=1

print "\nunordered comparison:"
for x in a:
    for y in b:
        if x == y:
            print x,y + " are Equal"
        elif x.replace("@","") == y.replace("@",""):
            print x,y + " Not completely Matched"
        else:
            print x,y + " Different"

输出:

enter image description here

Sets很容易逐个元素进行比较:

>>> a={'aaa@','bb','ccc@'}
>>> b={'aaa','bb@','ccc@'}
>>> c=a.copy()
>>> a-b
set(['aaa@', 'bb'])
>>> a-c
set([])

>>> d={"Product invoice","product verification","product completed@"}
>>> e= {"Product invoice","product verification@","product completed@"}
>>> d-e
set(['product verification'])
>>> d^e
set(['product verification@', 'product verification'])

然后使用空集或非空集的truthiness来获取所需内容:

>>> 'not matched' if a-b else 'matched'
'not matched'
>>> 'not matched' if a-c else 'matched'
'matched'

相关问题 更多 >