簡體   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