从列表中删除项目

我想删除以忽略列表中的重复项。例如,假设函数检查以 ''.'' 结尾的单词并将它们放入列表中。我想确保列表中没有重复的单词。

这是我到目前为止所拥有的:

def endwords(sent):
    list = []
    words = sent.split()
    for word in words:
        if "." in word:
            list.append(word)
        # bottom if statment does not work for some reason. thats the one i am trying to fix    
        if (word == list):
            list.remove(word)
    return list
威尔·达席尔瓦

在附加之前检查该单词是否已经在列表中如何,如下所示:

def endwords(sent):
     wordList = []
     words = sent.split()
     for word in words:
         if "." in word and word not in wordList:
             wordList.append(word)
     return wordList

您正在尝试检查 if word == list,但这是查看单词是否等于整个列表。要检查元素是否在 python 的容器中,可以使用in关键字。或者,要检查容器中是否没有某些东西,您可以使用not in.

另一种选择是使用集合:

def endwords(sent):
     wordSet = set()
     words = sent.split()
     for word in words:
         if "." in word:
             wordSet.add(word)
     return wordSet

为了让事情更清晰,这里有一个使用集合理解的版本:

def endwords(sent):
    return {word for word in sent.split() if '.' in word}

如果你想从这个函数中得到一个列表,你可以这样做:

def endwords(sent):
    return list({word for word in sent.split() if '.' in word})

由于您在问题中说要检查单词是否以“.”结尾,因此您可能还想像这样使用 endswith() 函数:

def endwords(sent):
    return list({word for word in sent.split() if word.endswith('.')})

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章