Python:如何从另一个集合中删除数据

2024-09-30 03:22:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个参考列表,例如:

dico = [ 'test', 'blabla' ]

我想删除其他列表中包含的这些项目:

^{pr2}$

结果应该是:

[ 'S02_ahah' ]

我尝试使用集合,但没有成功。有什么想法吗?在

谢谢:)


Tags: 项目test列表dicopr2blablas02ahah
2条回答

使用列表理解

bad_stubs = [ 'test', 'blabla' ]
input = [ 'S01_test', 'S02_ahah', 'S03_blabla' ]

#Gets an item from a list, if not there gives None
def lget(list, index, default=None):
    return list[index] if len(list) > index else default

results = [i for i in input if lget(i.split('_'), 1) not in bad_stubs]

发电机也可用于:

^{pr2}$

注意:i.split('_')[1]样式将错误,如果没有存根(项目在

您可以使用列表理解来完成此操作:

>>> [x for x in listTest if x.split('_')[1] not in dico]
['S02_ahah']

或使用^{}

^{pr2}$

如果您在python-3.x上,请记住用list()包装{a2},因为它返回一个迭代器:

>>> f = filter(lambda x: x.split('_')[1] not in dico, listTest)
>>> list(f)
['S02_ahah']

我可能更喜欢使用filter()lambda,而不是列表压缩,但是从一个非常基本的时间安排来看,理解似乎更快。在

相关问题 更多 >

    热门问题