RasmusGP
RasmusGP

Reputation: 5362

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.

Upvotes: 1

Views: 12072

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180540

You need to check each item in sort is not in each word not compare the tuple to each word which is what if not sort in word is doing :

from collections import defaultdict

items = defaultdict(int)
for word in item_list:
    if not any(ele in  word for ele in srt):
        items[word] += 1

Worth adding as it actually answers the question as asked. As @JonClements suggests simply use a Counter dict:

from collections import Counter
items = Counter(item for item in item_list if not any(word in item for word in sort)) 

using a defaultdict removes the need to check if word in items.

Upvotes: 1

Martin Zugnoni
Martin Zugnoni

Reputation: 1439

I know you are using python, but if the file is really huge, a good optimization would be to use some lower level commands, for example bash. Just as simple as this one-liner:

$ grep "text you are searching" my_file.txt | sort

Of course this bash code could be executed from python if needed, using the subprocess module.

Again, this is only worth if the file is huge and performance optimization matters. The bash commands will do the job way faster than a simple python loop.

I hope it helps.

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 118021

>>> 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"]

Upvotes: 6

Related Questions