繁体   English   中英

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

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

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

例如:

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

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

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

这应该这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM