同时过滤两个列表

X''*_*X'' 10 python filtering

我有三个清单:

del_ids = [2, 4]
ids = [3, 2, 4, 1]
other = ['a', 'b', 'c', 'd']
Run Code Online (Sandbox Code Playgroud)

我的目标是删除del_ids结果

ids = [3, 1]
other = ['a', 'd']
Run Code Online (Sandbox Code Playgroud)

我试图为要保持(mask = [id not in del_ids for id in ids])的元素做一个掩码,我计划在两个列表上应用这个掩码.

但我觉得这不是一个pythonic解决方案.你能告诉我怎样才能做得更好吗?

Mar*_*ers 13

压缩,过滤和解压缩:

ids, other = zip(*((id, other) for id, other in zip(ids, other) if id not in del_ids))
Run Code Online (Sandbox Code Playgroud)

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')]
Run Code Online (Sandbox Code Playgroud)