【问题标题】:Compare the strings with special characetr at end比较末尾带有特殊字符的字符串
【发布时间】:2015-03-13 14:41:10
【问题描述】:

我有两套

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

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

【问题讨论】:

  • 你有 sets,而不是列表。
  • 是的,那么如何使用集合进行比较
  • @abd,您能指定要与其他字符串比较的字符串吗?你看,你有集合而不是列表是一个问题,因为集合不是有序的,也没有办法告诉你要比较第一个集合的哪个元素与第二个集合的哪个元素。
  • 我想将第一个集合的所有元素与其他集合的所有元素进行比较
  • 我的字符串是第一组 {"Product invoice","product verification","product completed@"} 和 second set {"Product invoice","product verification@","产品完成@"}

标签: python string comparison


【解决方案1】:

列表示例:

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"

输出:

【讨论】:

  • 但是 OP 使用的是 sets,它们没有顺序,不能只是压缩在一起。另外,问题中哪里说元素可以如此整齐地配对?
  • questin 表示列表,使用 a[i] 和 b[j] 表示数学符号。当有人评论集合时,这个问题被排除在外。到那时我已经尝试过这个解决方案了。
  • 那个人就是我; OP 已确认他们有套装。
  • 此外,OP 还添加了:我想将第一个集合的所有元素与其他集合的所有元素进行比较。
  • 不,他问他是否可以看到一个 set atleast 的例子。
【解决方案2】:

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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 2015-07-15
    • 2019-08-03
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多