Home>
I want to achieve

I want to implement the process to remove the character string specified in the list from the following original data

original data

['oneXXXaaa','twoXXXbbb','three999aaa', '000111222', '999yyyy', '888bbb000']

Exclusion list

['XXX','bbb']

Processing result

['three999aaa', '000111222', '999yyyy']

Clogged point

I was able to determine if the specified character string was included by the following method.
When the target to be excluded is a list, I am wondering how to implement it to make it simple.

for target in target_list:
    if'except_word' in target:
  • Answer # 1

    If you want to write in an easy-to-understand manner, it is easier to understand by breaking it down into parts rather than doing it all at once.

    target_list = ['oneXXXaaa','twoXXXbbb',
                   'three999aaa', '000111222', '999yyyy', '888bbb000']
    word_list = ['XXX','bbb']
    def remove_target_including_a_word (targets, word):
        return [target for target in targets if not word in target]
    def remove_target_including_words (targets, words):
        for word in words:
            targets = remove_target_including_a_word (targets, word)
        return targets
    remove_target_including_words (target_list, word_list)

    If you want to write it short, it is as follows, but it is not easy to understand.

    target_list = ['oneXXXaaa','twoXXXbbb',
                   'three999aaa', '000111222', '999yyyy', '888bbb000']
    word_list = ['XXX','bbb']
    for word in word_list:
        target_list = [target for target in target_list if not word in target]
    print (target_list)

  • Answer # 2

    Built-inall ()By combining and the inclusion notation, you can write a little refreshingly.

    target_list = ['oneXXXaaa','twoXXXbbb','three999aaa', '000111222', '999yyyy', '888bbb000']
    word_list = ['XXX','bbb']
    result_list = []
    for target in target_list:
        if all (word not in target for word in word_list):
            result_list.append (target)

  • Answer # 3

    If you don't care about the processing speed, you can double the loop.

    target_list = ['oneXXXaaa','twoXXXbbb',
                   'three999aaa', '000111222', '999yyyy', '888bbb000']
    word_list = ['XXX','bbb']
    result_list = []
    for target in target_list:
        for word in word_list:
            if word in target:
                break
        else: else:
            result_list.append (target)
    print (result_list)

  • Answer # 4

    This is a code that includes bsdfan's code. It's almost the same, but I'll show you.

    target_list = ['oneXXXaaa','twoXXXbbb','three999aaa', '000111222', '999yyyy', '888bbb000']
    word_list = ['XXX','bbb']
    result_list = [target for target in target_list
                   if all (word not in target for word in word_list)]
    print (result_list) # ['three999aaa', '000111222', '999yyyy']