比较两个单独的字符串输入并找出它们的共同点
Comparing two separate string inputs and finding what they have in common
我确信有更好的方法来描述我的问题(因此我在 google 上找不到太多内容),但我想比较两个单独的字符串并提取它们共有的子字符串.
假设我有一个带有两个参数的函数,"hello,world,pie"
和 "hello,earth,pie"
我要return"hello,pie"
我该怎么做?这是我目前所拥有的
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']
>>> a = "hello,world,pie"
>>> b = "hello,earth,pie"
>>> ','.join(set(a.split(',')).intersection(b.split(',')))
'hello,pie'
try this
a="hello,world,pie".split(',')
b="hello,earth,pie".split(',')
print [i for i in a if i in b]
使用set() & set():
def compare(first, second):
return ','.join(set(first.split(',')) & set(second.split(',')))
compare("hello,world,pie", "hello,earth,pie")
'hello,pie'
我确信有更好的方法来描述我的问题(因此我在 google 上找不到太多内容),但我想比较两个单独的字符串并提取它们共有的子字符串.
假设我有一个带有两个参数的函数,"hello,world,pie"
和 "hello,earth,pie"
我要return"hello,pie"
我该怎么做?这是我目前所拥有的
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']
>>> a = "hello,world,pie"
>>> b = "hello,earth,pie"
>>> ','.join(set(a.split(',')).intersection(b.split(',')))
'hello,pie'
try this
a="hello,world,pie".split(',')
b="hello,earth,pie".split(',')
print [i for i in a if i in b]
使用set() & set():
def compare(first, second):
return ','.join(set(first.split(',')) & set(second.split(',')))
compare("hello,world,pie", "hello,earth,pie")
'hello,pie'