简体   繁体   中英

Remove (from list) all the items which contains other item - Python

I have some list, and I want to remove from it every item which contains other item, except the item itself.

For example:

if my list looking like this:

["AAA", "STACK_OVERFLOWAAAAAAA", "123AAAAA45678", "123456", "FOO", "DIR", "ITEM", ........]

Now, I want that the code will remove all the items which includes "AAA" in it. After that scan I want that the code will remove all the items which includes "123456" in it (if there are), and so on.

The wanted output should be like this:

lst = ["AAA", "123456", "FOO", "DIR", "ITEM", ........]

This is my code, and from some reason, it doesn't work...

lst = ["AAA",
   "STACK_OVERFLOWAAAAAAA",
   "123AAAAA45678",
   "123456",
   "FOO",
   "DIR",
   "ITEM"
   "AAAAA1234",
   "VDFKGMGDFRAAAAAAAAAA",
   "FNHBFDGBNDFGFHFGDUHGDRGJRAAAAAAAAA",
   "6545154DDFEFRGAAAAAAA",
   "123",
   "ABC",
   "abc"]

# The meaning of this variable is to indicate if the sub - item has already found in the list.
# If so, the code should remove all the next items which contains the current sub - item
AlreadyFound = False

# ItemToSearch = the sub - item which the program should search in the other list - items.
for ItemToSearch in lst:

    # Start the loop and search the sub - item in every item which in the list.
    for ItemToCheck in lst:

        # If the current item contains the sub - item..
        if (ItemToSearch in ItemToCheck):

            # If the sub - item has already found in the list
            if (AlreadyFound == True):

                # Delete the current item from the list
                del CurrItem
            else:
                AlreadyFound = True

print "\n".join(lst)
input()

I will glad to get some help. Thank you.

This should do it:

>>> lst = ["AAA", "STACK_OVERFLOWAAAAAAA", "123AAAAA45678", "123456", "FOO", "DIR", "ITEM"]
for i, x in enumerate(lst):
    lst[i+1:] = [y for y in lst[i+1:] if x not in y]
...     
>>> lst
['AAA', '123456', 'FOO', 'DIR', 'ITEM']
>>> 

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