首页 > 解决方案 > 从字符串列表中删除多余的组成字符串

问题描述

我看到昨天发布的一个问题,关于这样的列表如何:

my_list = ["lol hi there", "hi", "i like", "i like apples", "goodbye"]

可以转换为:

my_list = ["lol hi there", "i like apples", "goodbye"]

其中字符串喜欢"hi""i like"从 中删除my_list,因为"hi"和分别"i like"在字符串"lol hi there"和中找到"i like apples"。它们被从列表中删除纯粹是因为它们出现在列表中的任何其他字符串中,而不管列表中的索引或字符串中的位置。

另一个例子是:

my_list1 = ["hello", "he", "go", "goodbye", "good", ]

将转换为:

my_list1 = ["hello", "goodbye"]

由于"he"in "hello", and "go", 以及"good", in的重复出现"goodbye"

我为此尝试使用以下方法:

import re

my_list = ["lol hi there", "hi", "i like", "i like apples", "goodbye"]

for x in my_list:
    for y in my_list:
        if x != y:
            if len(x) < len(y):
                if re.search(x, y):
                    my_list.pop(my_list.index(x))
            else:
                if re.search(y, x):
                    my_list.pop(my_list.index(y))
print(my_list)

这让我得到了我想要的。用户已经删除了他们的问题,但我想知道一种更简洁的方法来解决这个问题。有人可以帮帮我吗?

标签: pythonregex

解决方案


如果您不关心使用正则表达式,则可以使用in运算符。

my_list = ["lol hi there", "hi", "i like", "i like apples", "goodbye"]
filtered_list = []
for i,si in enumerate(my_list):
    # search each element against every other element in the list, j != i ensures it doesnt compare to self.
    inlist = any( [ si in xi for j, xi in enumerate(my_list) if j != i] )
    if not inlist:
        filtered_list.append( si )
print( filtered_list )

或者,如果您更喜欢一行:

filtered_list = [ si for i, si in enumerate( my_list ) if not any( [si in sii for j, sii in enumerate(my_list) if j != i] )]
print( filtered_list )

推荐阅读