简体   繁体   中英

How to filter out list elements based on if they contain a substring from another list in Python

I have a list of strings like so called 'main_list':

['Hello_Kitty [data]', 'abc_xyz [data]']

and another list called 'ids'

[abc, xyz]

I create this list by looking through 'contents_list' and appending to main_list if 'data' is found in the row entry (contents_list) is just a list of strings.

for entry in contents_list:
    if 'data' in entry:
        main_list.append(entry)

How can I filter out entries to not append anything to main_list if it contains an id from 'ids' in the substring?

I want to end up with this:

['Hello_Kitty [data]']
main_list = ['Hello_Kitty [data]', 'abc_xyz [data]']
ids = ['abc', 'xyz']

filtered_output=[]

for item in main_list:
    blocked=False
    for id in ids:
        if id in item:
            blocked=True
    if blocked == False:
        filtered_output.append(item)

Output:

['Hello_Kitty [data]']

You'll need to check for every id whether it is in the string before appending. My preferred method is to use a list comprehension.

I'll use the list comprehension to make a list which contains all the ids a string contains. If this list's length is more than 0, then that string is not appended.

[id for id in ids if id in entry] will be the list comprehension. This will, for each element of ids, check if that element is a substring of the entry. If yes, that id goes into the list comprehension.

I'll use the condition len( [id for id in ids if id in entry] ) == 0 with another if to get the job done. If the length is 0, no id is a substring of entry.

for entry in contents_list:
    if 'data' in entry:
        if len( [id for id in ids if id in entry] ) == 0:
            main_list.append(entry)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM