python筛分法

2024-04-25 16:49:56 发布

您现在位置:Python中文网/ 问答频道 /正文

假设你得到一个字符串。示例:

s = "FishCatRainComp_CatWater_JamDog"

你定义了一个筛子。一个筛子-是一个单词列表,你想赶上(一次,如果多次出现在s),例如:

sieve = ["Dog","Cat"]

在我们的例子中,将一根细绳穿过筛子会产生一根细绳,即:

out = "CatDog"

达到这个结果最优雅的方法是什么?你知道吗


Tags: 字符串示例列表定义out单词例子cat
2条回答

如果要保持字符串在s中出现的顺序,可以执行以下操作:

found = re.findall('({})'.format('|'.join(re.escape(w) for w in sieve)), s)

然后您必须remove the repeated strings

def remove_repeated(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

print(''.join(remove_repeated(found)))

这个解可能更长,但它有更好的渐近性

否则,可以按index对字符串进行排序:

>>> sorted([word for word in sieve if word in s], key=lambda word: s.index(word))

下面是我想到的最优雅的方式:

''.join([word for word in sieve if word in s])

假设输入字符串中单词的顺序应反映在输出字符串中:

def SieveString(s,sieve):
    zipped = zip(sieve,[s.index(word) for word in sieve if word in s])
    zipped.sort(key=lambda x:x[1])
    return ''.join(word for word,index in zipped)

相关问题 更多 >