Python 比较两个单独的字符串输入并找出它们的共同点
我确信有更好的方法来描述我的问题,因此我在google上没有找到很多东西,但我想比较两个单独的字符串,并提取它们的共同子字符串 假设我有一个函数,它有两个参数,hello,world,pie和hello,earth,pie 我想回你好,派 我怎么能这样做?这是我到目前为止所拥有的Python 比较两个单独的字符串输入并找出它们的共同点,python,python-3.x,Python,Python 3.x,我确信有更好的方法来描述我的问题,因此我在google上没有找到很多东西,但我想比较两个单独的字符串,并提取它们的共同子字符串 假设我有一个函数,它有两个参数,hello,world,pie和hello,earth,pie 我想回你好,派 我怎么能这样做?这是我到目前为止所拥有的 def compare(first, second): save = [] for b, c in set(first.split(',')), set(second.split(',')):
def compare(first, second):
save = []
for b, c in set(first.split(',')), set(second.split(',')):
if b == c:
save.append(b)
compare("hello,world,pie", "hello,earth,pie")
试着这样做:
>>> def common(first, second):
... return list(set(first.split(',')) & set(second.split(',')))
...
>>> common("hello,world,pie", "hello,earth,pie")
['hello', 'pie']
试试这个
使用集合(&S):
使用这两个集合的集合。你试过使用正则表达式吗?这很有效,谢谢!请解释一下怎么了。我返回了问题中给出的输出字符串
>>> a = "hello,world,pie"
>>> b = "hello,earth,pie"
>>> ','.join(set(a.split(',')).intersection(b.split(',')))
'hello,pie'
a="hello,world,pie".split(',')
b="hello,earth,pie".split(',')
print [i for i in a if i in b]
def compare(first, second):
return ','.join(set(first.split(',')) & set(second.split(',')))
compare("hello,world,pie", "hello,earth,pie")
'hello,pie'