📜  Python|从字符串列表中删除冗余子字符串

📅  最后修改于: 2022-05-13 01:54:36.924000             🧑  作者: Mango

Python|从字符串列表中删除冗余子字符串

给定字符串列表,任务是删除所有字符串,它们是其他字符串的子字符串。

方法 #1:使用 enumerate() + join() + sort()

上述功能的组合可以用来解决这个问题。在此,首先对长度参数进行排序,并将当前单词与其他单词进行检查,如果它作为子字符串出现,如果是,则将其从过滤结果中排除。

Python3
# Python3 code to demonstrate working of
# Remove Reduntant Substrings from Strings List
# Using enumerate() + join() + sort()
 
# initializing list
test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# using loop to iterate for each string
test_list.sort(key = len)
res = []
for idx, val in enumerate(test_list):
     
    # concatenating all next values and checking for existence
    if val not in ', '.join(test_list[idx + 1:]):
        res.append(val)
 
# printing result
print("The filtered list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Remove Reduntant Substrings from Strings List
# Using list comprehension + join() + enumerate()
 
# initializing list
test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension to iterate for each string
# and perform join in one liner
test_list.sort(key = len)
res = [val for idx, val in enumerate(test_list) if val not in ', '.join(test_list[idx + 1:])]
 
# printing result
print("The filtered list : " + str(res))


输出
The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks']
The filtered list : ['Gfg is best', 'Gfg is for Geeks']

方法#2:使用列表理解 + join() + enumerate()

上述功能的组合可以用来解决这个问题。在此,我们以与上述类似的方式执行任务,不同之处在于列表理解的方式更紧凑。

Python3

# Python3 code to demonstrate working of
# Remove Reduntant Substrings from Strings List
# Using list comprehension + join() + enumerate()
 
# initializing list
test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension to iterate for each string
# and perform join in one liner
test_list.sort(key = len)
res = [val for idx, val in enumerate(test_list) if val not in ', '.join(test_list[idx + 1:])]
 
# printing result
print("The filtered list : " + str(res))
输出
The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks']
The filtered list : ['Gfg is best', 'Gfg is for Geeks']