Python-相交字符串 [英] Python - Intersectiing strings
问题描述
尝试编写一个for函数,该函数接受两个字符串,并返回按在第一个字符串中出现的顺序相交的字符.
Trying to write a for function that takes two strings and returns the characters that intersect in the order that they appear in the first string.
这是我尝试过的:
def strIntersection(str1, str2):
for i in str1:
str3 = ''
str3 = str3.join(i for i in str1 if i in str2 not in str3)
return str3
str1 = 'asdfasdfasfd'
str2 = 'qazwsxedc'
strIntersection(str1,str2)
=> 'asdasdasd'
但是我只希望交集字符以第一个字符串的顺序出现一次,即. 'asd'
however I only want the the intersection characters to appear once and in order of the first string ie. 'asd'
任何人都可以帮忙吗?
我在其他论坛上发现了一些类似的问题,但是解决方案似乎都涉及列表,而我希望输出为字符串
I've found some similar problems on other forums but the solutions all seem to involve lists whereas I'd like my output to be a string
推荐答案
以另一种方式检查事件是否得到控制,并且不发出已经发出的字符:
Check for occurances the other way around to get the order under control, and don't emit characters you've already emitted:
def strIntersection(s1, s2):
out = ""
for c in s1:
if c in s2 and not c in out:
out += c
return out
可以肯定的是,您可以将其重写为列表理解,但是我觉得这更容易理解.
Sure you could re-write it to be a list comprehension, but I find this easier to understand.
对于您的测试数据,我们得到:
For your test data, we get:
>>> strIntersection('asdfasdfasfd' , 'qazwsxedc')
'asd'
这篇关于Python-相交字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!