简体   繁体   English

获得两个字符串(在python中)之间对称差异的最佳有效方法是什么?

[英]What is the best effective way to get symmetric difference between two strings(in python)?

Example: If there are two strings:- s1 = 'cde' s2 = 'abc'示例:如果有两个字符串:- s1 = 'cde' s2 = 'abc'

Output: 'deab' Output:'deab'

I converted the string into a list and compared two lists.我将字符串转换为列表并比较了两个列表。

a = 'cde'
b = 'abc'
list1 = list(a)
list2 = list(b)

diff = []
for item in list1:
      if item not in list2:
            diff.append(item)
for item in list2:
      if item not in list1:
            diff.append(item)
diff = ' '.join(map(str, diff)).replace(' ','')

print(diff)

Is there any other way to solve this problem without converting it into the list?有没有其他方法可以在不将其转换为列表的情况下解决此问题? I appreciate your help.我感谢您的帮助。 Thanks in advance.提前致谢。

You can convert each string to a set then use symmetric_difference , then finally str.join back into a single string您可以将每个字符串转换为一个set ,然后使用symmetric_difference ,最后str.join回单个字符串

>>> ''.join(set(a).symmetric_difference(b))
'daeb'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查找 python 中两个整数列表之间差异的有效方法 - Effective way of finding difference between two lists of integers in python Python 2.7中的集合对称差异和带有突变的集合对称差异有什么区别? - What is the difference between set symmetric difference and set symmetric difference with mutation in Python 2.7? 找到两个字符串之间交集的最佳方法是什么? - What's the best way to find the intersection between two strings? 在两个非常大的文件中使用 python 比较字符串的最有效方法是什么? - What is the most effective way to compare strings using python in two very large files? Python - 两个字符串之间的区别 - Python - difference between two strings 如何在Python中获取两个字符串与时间和工作日的差异 - How to get Difference between two strings with time and weekday in Python 在两点之间找到字符串的最佳方法 - Best way to find strings between two points 在python中两个对象之间存储和使用信息的最佳方法是什么? - What is the best way to store and use information between two objects in python? 使用 python 中的对称差异从两个字符串生成 Anagrams 的计算成本 - Computational cost of making Anagrams from two strings using symmetric difference in python 在Python中找到两个时间字符串之间的差异 - Find difference between two time strings in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM