python - 同时过滤两个列表

标签 python filtering

我有三个列表:

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/

相关文章:

python - Pandas 中 boolean 索引的逻辑运算符

python - 循环字典的内部列表,添加缺失的月份

python - 多余的 python 参数

python - Pandas:从 3 列创建时间戳:月、日、小时

c++ - 如何在 C++ 中删除数组中小于 X 的整数?

asp.net-mvc - ASP.NET MVC : Restricting access using url

python - 根据子字符串在日志文件中查找特定行 - Python

python - 如何在 Pandas 中使用 Apply 函数来应用/lambda?

javascript - 如何使用 jQuery 按数据属性过滤选项?

带条件和列的Python过滤数据框