2 回答

TA贡献1806条经验 获得超5个赞
这是一个快速而肮脏的(暴力)解决方案。
假定您具有以下要比较的字符串,因为您提到的分隔符(或定界符)为“”。
>>> s = "herearesomewordsinastringinsomeorder"
现在假设您有一个list l,要与之进行比较的单词s并进行记录。
>>> l = ['string', 'the', 'in', 'appear', 'words', 'these', 'do']
然后,您可以初始化一个新列表,newlist以l按照出现的顺序记录单词s。
>>> newlist = []
然后,您可以编写一个for-each-in循环:
>>> for length in range(len(s)):
... for word in l:
... if word in s[:length+1] and word not in newlist:
... newlist.append(word)
经评估,这将为您提供:
>>> newlist
['words', 'in', 'string']
按照他们出现的顺序s。

TA贡献1829条经验 获得超7个赞
您也许可以使用表达式来做到这一点!
def fn(s, input_list):
return list(x for x in s.split() if x in input_list)
通过首先将您的字符串s放入列表中,然后对其进行遍历,找到其中的所有成员,可以进行此操作input_list
>>> fn("one two three", ["three", "two", "missing"])
['two', 'three']
对于小字符串,这应该是完全合理的
如果要创建新字符串,可以使用 " ".join()"
>>> " ".join(fn("one two three", ["three", "two", "missing"]))
'two three
如果始终要返回新的字符串,则可以直接返回联接的值,而不必创建新列表。
def fn(s, input_list):
return " ".join(x for x in s.split() if x in input_list)
添加回答
举报