从列表中删除包含其他项目的所有项目 - Python

时间:2014-02-14 13:54:51

标签: python list

我有一些列表,我想从中删除包含其他项目的所有项目,除了项目本身。

例如:

如果我的列表看起来像这样:

  

[“AAA”,“STACK_OVERFLOWAAAAAAAA”,“123AAAAA45678”,“123456”,“FOO”,“DIR”,“ITEM”,........]

现在,我希望代码将删除其中包含“AAA”的所有项目。 在那次扫描之后,我希望代码将删除其中包含“123456”的所有项目(如果有的话),依此类推。

想要的输出应该是这样的:

  

lst = [“AAA”,“123456”,“FOO”,“DIR”,“ITEM”,........]

这是我的代码,由于某种原因,它不起作用......

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()

我很乐意得到一些帮助。 谢谢。

1 个答案:

答案 0 :(得分:3)

这应该这样做:

>>> 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']
>>>