我有三个列表:
del_ids = [2, 4]
ids = [3, 2, 4, 1]
other = ['a', 'b', 'c', 'd']
我的目标是删除 del_ids
,结果是
ids = [3, 1]
other = ['a', 'd']
我尝试为要保留的元素做一个掩码 (mask = [id not in del_ids for id in ids]
),我计划在两个列表上应用这个掩码。
但我觉得这不是pythonic的解决方案。你能告诉我如何才能做得更好吗?
最佳答案
再次压缩、过滤和解压:
ids, other = zip(*((id, other) for id, other in zip(ids, other) if id not in del_ids))
zip()
调用将每个 id
与相应的 other
元素配对,生成器表达式过滤掉 所在的任何对id
列在 del_ids
中,然后 zip(*..)
将剩余的对再次整理到单独的列表中。
演示:
>>> del_ids = [2, 4]
>>> ids = [3, 2, 4, 1]
>>> other = ['a', 'b', 'c', 'd']
>>> zip(*((id, other) for id, other in zip(ids, other) if id not in del_ids))
[(3, 1), ('a', 'd')]
关于python - 同时过滤两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17995302/