如何从列表中删除项目的部分匹配项目
How to remove items from a list where partial matches for items exist in the list
如果我有一个列表,其中的项目与列表中的其他项目有部分匹配,例如下面,其中 'bob'
是 'bob1'
和 [=15= 中的部分匹配], 我想删除部分匹配项 ('bob1'
, 'bob2'
, 'peter2'
)
例如我想从这里开始:
lst = ['bob', 'bob1', 'bob2', 'peter', 'peter2']`
对此:
lst = ['bob', 'peter']
我有这个可以用,但我想知道是否有更简洁的方法?
lst = ['bob', 'bob1', 'bob2', 'peter', 'peter2']
removeIndices = []
for i, itemi in enumerate(lst):
for j, itemj in enumerate(lst):
if itemi in itemj and itemi != itemj:
removeIndices.append(j)
for i in sorted(removeIndices, reverse=True):
del lst[i]
您可以将 all()
与累积结果的列表一起使用:
result = []
for item in lst:
if all(substr not in item for substr in result):
result.append(item)
这输出:
['bob', 'peter']
与您现有的方法相比,这有两个优点:
- 无需在原始列表上重复调用
del
。如果你想保留原来的列表,你可以。 (重复调用del
也很慢。)
- 不需要双
for
循环。这种语法(在我看来)更清晰、更直观。
@BrokenBenchmark 的解决方案仅适用于排序列表。这是一个也适用于未排序列表的解决方案。
lst = ['peter2', 'bob2', 'bob', 'bob1', 'peter']
[item for item in lst if sum(substr not in item for substr in lst)==len(lst)-1]
输出:
['bob', 'peter']
如果我有一个列表,其中的项目与列表中的其他项目有部分匹配,例如下面,其中 'bob'
是 'bob1'
和 [=15= 中的部分匹配], 我想删除部分匹配项 ('bob1'
, 'bob2'
, 'peter2'
)
例如我想从这里开始:
lst = ['bob', 'bob1', 'bob2', 'peter', 'peter2']`
对此:
lst = ['bob', 'peter']
我有这个可以用,但我想知道是否有更简洁的方法?
lst = ['bob', 'bob1', 'bob2', 'peter', 'peter2']
removeIndices = []
for i, itemi in enumerate(lst):
for j, itemj in enumerate(lst):
if itemi in itemj and itemi != itemj:
removeIndices.append(j)
for i in sorted(removeIndices, reverse=True):
del lst[i]
您可以将 all()
与累积结果的列表一起使用:
result = []
for item in lst:
if all(substr not in item for substr in result):
result.append(item)
这输出:
['bob', 'peter']
与您现有的方法相比,这有两个优点:
- 无需在原始列表上重复调用
del
。如果你想保留原来的列表,你可以。 (重复调用del
也很慢。) - 不需要双
for
循环。这种语法(在我看来)更清晰、更直观。
@BrokenBenchmark 的解决方案仅适用于排序列表。这是一个也适用于未排序列表的解决方案。
lst = ['peter2', 'bob2', 'bob', 'bob1', 'peter']
[item for item in lst if sum(substr not in item for substr in lst)==len(lst)-1]
输出:
['bob', 'peter']