Search code examples
pythonlistcontain

Check if string contains any elements from list


Check Below for better explaination I have a long list of items in a file thats read line by line, and i want to sort all out that has a specific string in it. If the word does not contain any of the elements in sort, then it will be added to a dictionary. How do i do that? I have read some other situations on this website, but i just don't get it... So this might be a duplicate, but i need someone to explain me how to do this. (Yes the items is from the game 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

Already got it answered, but just to make the question clear. I want to run sort the list: item_list and i wanted to do that by making a array: sort so it checks each element in item_list and check if the element have any of the elements from sort in it. If it didn't it added the element to a dictionary.


Solution

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

    You can use a list comprehension with any to check if any of the disallowed substrings are in the current element

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