查找连续单词中的单词

2024-10-02 08:18:48 发布

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

def sucontain(A):
    C = A.split()
    def magic(x):
        B = [C[i]==C[i+1] for i in range(len(C)-1)]
        return any(B)
    N = [x for x in C if magic(x)]
    return N
Phrase = "So flee fleeting candy can and bandage"
print (sucontain(Phrase))

这个函数的目标是创建一个单词列表,这些单词位于每个连续单词的内部。例如,函数将字符串“”So fleed fleeting candy can and bandage“”作为输入,并返回['fleed','and'],因为fleed在fleeting(下一个单词)中,'and'在'bandage'中。如果没有找到类似的案例,则应返回空列表[]。我的代码现在返回的是[],而不是['fleed','和']。有人能指出我做错了什么吗?谢谢


Tags: andinforreturnsodefmagic单词
3条回答

展望未来可能会有问题。与其测试当前单词是否在下一个单词中,不如检查前一个单词是否在当前单词中。这几乎总是让事情变得简单。你知道吗

另外,使用描述性变量名,而不是CAxBNmagic。你知道吗

def succotash(text):   # okay, so that isn't very descriptive
    lastword = " "     # space won't ever be in a word
    results = []
    for currentword in text.split():
         if lastword in currentword:
             results.append(currentword)
         lastword = currentword
    return results

print succotash("So flee fleeting candy can and bandage")

你的magic函数肯定有问题。它接受x作为参数,但不在任何地方使用它。你知道吗

下面是一个不使用附加函数的替代版本:

def sucontain(A):
    C = A.split()
    return [w for i, w in enumerate(C[:-1]) if w in C[i+1]]

enumerate()函数允许我们将索引和值循环在一起,这使得执行测试非常简单。C[i+1]是下一个值,w是当前值,因此w in C[i+1]检查当前值是否包含在下一个值中。我们使用C[:-1]确保在最后一项之前停止一项,否则C[i+1]将导致索引器错误。你知道吗

只要把连续的单词配对,就可以很容易地理解

>>> s = "So flee fleeting candy can and bandage"
>>> words = s.split()
>>> [i for i, k in zip(words, words[1:]) if i in k]
['flee', 'and']

相关问题 更多 >

    热门问题