Skip to main content
 首页 » 编程设计

python之检查字符串是否包含列表中的任何元素

2025年05月04日24jiqing9006

检查下面以获得更好的解释 我在逐行读取的文件中有一长串项目,我想对其中包含特定字符串的所有项目进行排序。如果单词不包含排序中的任何元素,那么它将被添加到字典中。我怎么做?我已经阅读了该网站上的其他一些情况,但我就是不明白......所以这可能是重复的,但我需要有人向我解释如何做到这一点。 (是的,这些元素来自游戏 TF2)

item_list = ("Non-Tradable Ubersaw", "Screamin' Eagle", "'Non-Craftable Spy-cicle" 
 
sort = ("Non-Tradable", "Non-Craftable") # The items that are not allowed 
for word in item_list: 
    if not sort in word: 
        if word in items: # add to the dictionary 
            items[word] += 1 
        else: 
            items[word] = 1 

已经得到答案,但只是为了把问题弄清楚。 我想对列表进行排序:item_list 我想通过创建一个数组来做到这一点:sort 所以它检查 item_list 中的每个元素并且检查元素中是否包含 sort 中的任何元素。如果没有,它会将元素添加到字典中。

请您参考如下方法:

>>> item_list = ["Non-Tradable Ubersaw", "Screamin' Eagle", "'Non-Craftable Spy-cicle"] 
>>> not_allowed = {"Non-Tradable", "Non-Craftable"} 

您可以使用带有 any 的列表理解来检查当前元素中是否有任何不允许的子字符串

>>> filtered = [i for i in item_list if not any(stop in i for stop in not_allowed)] 
>>> filtered 
["Screamin' Eagle"]