Python - Remove any element from a list of strings that is a substring of another element

前端 未结 8 2106
清酒与你
清酒与你 2020-12-06 10:09

So starting with a list of strings, as below

string_list = [\'rest\', \'resting\', \'look\', \'looked\', \'it\', \'spit\']

I wan

8条回答
  •  离开以前
    2020-12-06 10:50

    Here's a possible solution:

    string_list = ['rest', 'resting', 'look', 'looked', 'it', 'spit']
    def string_set(string_list):
        return set(i for i in string_list 
                   if not any(i in s for s in string_list if i != s))
    
    print(string_set(string_list))
    

    prints out:

    set(['looked', 'resting', 'spit'])
    

    Note I create a set (using a generator expression) to remove possibly duplicated words as it appears that order does not matter.

提交回复
热议问题