Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何循环遍历一个列表,排除属于另一个列表的一些数字?_Python_List_Loops_For Loop - Fatal编程技术网

Python:如何循环遍历一个列表,排除属于另一个列表的一些数字?

Python:如何循环遍历一个列表,排除属于另一个列表的一些数字?,python,list,loops,for-loop,Python,List,Loops,For Loop,我需要遍历一个包含100000个元素的列表“a”。但是我需要跳过其中的一些,特别是我想跳过写在另一个列表“B”中的元素。 执行此操作的最佳方法是什么?您可以使用过滤器: a = [0, 1, 2, 3, 4] b = [1, 2] list(filter(lambda el: el not in b, a)) # [0, 3, 4] 如果需要迭代元素,请删除包装过滤器的列表: for el in filter(lambda el: el not in b, a): do_somethi

我需要遍历一个包含100000个元素的列表“a”。但是我需要跳过其中的一些,特别是我想跳过写在另一个列表“B”中的元素。 执行此操作的最佳方法是什么?

您可以使用过滤器:

a = [0, 1, 2, 3, 4]
b = [1, 2]
list(filter(lambda el: el not in b, a))
# [0, 3, 4]
如果需要迭代元素,请删除包装过滤器的
列表

for el in filter(lambda el: el not in b, a):
    do_something()
或者,也可以通过列表理解实现相同的功能,列表理解在语义上基本相同:

[el for el in a if el not in b]
# [0, 3, 4]
请记住,在这两个版本中,您将对b的元素执行线性搜索。 如果这个列表相当长,这可能会变得非常缓慢。 一个更有效的方法(如评论中所建议的)是将b设为集合而不是列表。 这只需要对b的元素进行修改


B
中创建一个集合,并检查每个元素是否在B中
。您编写了代码吗?
B=set(B);只有_in_A=[x代表A中的x,如果x不代表B]
。。。或者,如果您不关心
A
中的多个重复值,则将
A
转换为
set
。最佳值的可能重复取决于“最佳”的含义(运行时?内存?代码准确度?)和列表的内容(大小?排序?)以及所需的迭代顺序。
bset = set(b)
[el for el in a if el not in bset]
# [0, 3, 4]