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

前端 未结 8 2112
清酒与你
清酒与你 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条回答
  •  萌比男神i
    2020-12-06 10:54

    Here's is the efficient way of doing it (relative to the above solutions ;) ) as this approach reduces the number of comparisons between the list elements a lot. If I have a huge list, I'd definitely go with this and of course you can morph this solution into a lambda function to make it look small:

    string_list = ['rest', 'resting', 'look', 'looked', 'it', 'spit']
    for item in string_list: 
      for item1 in string_list:
        if item in item1 and item!= item1:
          string_list.remove(item)
    
    print string_list
    

    Output:

    >>>['resting', 'looked', 'spit']
    

    Hope it helps !

提交回复
热议问题