在字符串列表中,如何删除属于列表中其他字符串的字符串?
下面是一个示例。
lst = ['Hello World', 'Hello', 'This is test', 'is test']
我只想得到['Hello World', 'This is test']
作为输出。
您可以应用list comprehension
以过滤列表。
此外,通过将lambda
表达式用作参数来使用filter
方法。
lst = ['Hello World', 'Hello', 'This is test', 'is test']
lst = [string for string in lst if len(list(filter(lambda x: string in x, lst))) == 1]
输出
['Hello World', 'This is test']
您可以使用any
:
lst = ['Hello World', 'Hello', 'This is test', 'is test']
new_results = [a for i, a in enumerate(lst) if any(h in a and c != i for c, h in enumerate(lst))]
输出:
['Hello World', 'This is test']