Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字符串列表中删除冗余的组成字符串_Python_Regex - Fatal编程技术网

Python 从字符串列表中删除冗余的组成字符串

Python 从字符串列表中删除冗余的组成字符串,python,regex,Python,Regex,我昨天看到一个问题,关于这样的列表: my_list = ["lol hi there", "hi", "i like", "i like apples", "goodbye"] 可转换为: my_list = ["lol hi there", "i like apples", "goodbye"] 其中,由于在字符串“hi”和“i like”中分别找到“hi”和“i like”的方式,从我的列表中删除了“hi”和“i like apples”。它们从列表中删除纯粹是因为它们出现在列表中找到

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

my_list = ["lol hi there", "hi", "i like", "i like apples", "goodbye"]
可转换为:

my_list = ["lol hi there", "i like apples", "goodbye"]
其中,由于在字符串
“hi”
“i like”
中分别找到
“hi”
“i like”
的方式,从
我的列表中删除了
“hi”
“i like apples”
。它们从列表中删除纯粹是因为它们出现在列表中找到的任何其他字符串中,而与列表中的索引或字符串中的位置无关

另一个例子是:

my_list1 = ["hello", "he", "go", "goodbye", "good", ]
将转换为:

my_list1 = ["hello", "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)
重新导入
我的清单=[“你好”,“你好”,“我喜欢”,“我喜欢苹果”,“再见”]
对于my_列表中的x:
对于我的\u列表中的y:
如果x!=y:
如果len(x)

这让我得到了我想要的。用户已经删除了他们的问题,但我想知道一种更简洁的方法。谁能帮我一把吗?

如果你不想使用正则表达式,你可以使用
中的
操作符

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 )

需要删除的“小”/“冗余”字符串的条件是什么?@moys它指的是已在列表中的另一个字符串中找到的字符串。例如,“hi”和“i like”由于分别在字符串“lol hi there”和“i like apples”中重复出现而从列表中删除。当
[“hi”,“lol hi there”,“i like apples”,“i like”,“再见”]
时,输出将是什么?您的主要工作是以清晰明确的方式陈述问题。你很少能用一个例子来提问(尽管例子很有用)。您需要说明是否保留数组元素的条件。我猜您没有保留“我喜欢”,因为下一个元素以“我喜欢”开头。如果“我喜欢苹果”出现在数组的后面或“我喜欢”之前,该怎么办?大概你没有保留“hi”,因为这个词以前出现在字符串中。如果第一个元素是“高山”,你会保留它吗?请编辑问题以澄清。@Ch3steR它将通过
my_list=[“你好”,“我喜欢苹果”,“再见”]