且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

要从列表中删除项目?

更新时间:2023-12-05 15:40:46

棘手的问题:)


尝试了一会儿在放弃之前我虽然使用了2个相同的列表。

Tricky problem :)

After trying a while, before giving up I though about using 2 identical lists.

展开an> | 选择 | Wrap | 行号


不喜欢过滤器?你毕竟是过滤了;)


两种可能性:


x = [要过滤的列表]

y = [要过滤的术语列表]


过滤器(lambda x:x不在y,x)





[如果p不在y,则p为p in x]


et voila。


list comp is可能更快(我还没有测试过)
no love for filter? you are filtering after all ;)

two possibilities:

x =[list to be filtered]
y =[list of terms to be filtered out]

filter(lambda x: x not in y,x)

or

[p for p in x if p not in y]

et voila.

list comp is probably faster (i haven''t tested)


非常好的benjumanji。 filter()解决方案很好,但由于速度和可读性,我更喜欢列表理解。使用 timeit()进行测试时,列表理解速度提高了两倍。
Very good benjumanji. The filter() solution is fine, but I prefer the list comprehension due to its speed and readability. The list comprehension was twice as fast when tested with timeit().