如果我有一个列表,其中包含与列表中其他项目部分匹配的项目,如下所示,其中 'bob'
是 'bob1' 内的部分匹配
和 'bob2'
,我想删除这些部分匹配的项目 ('bob1'
, 'bob2'
, '彼得2'
)
例如我想从这里开始:
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
循环不是必需的。 (在我看来)这种语法更清晰、更直观。
关于python - 如何从列表中删除项目中存在部分匹配项的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72107751/