从另一个列表中删除一个列表的元素
是否有一种Pythonic将元素从一个列表中删除到另一个列表的方法? (不是删除所有重复项)
例如,给定[1、2、2、3、3、3](原始列表)和[1、2、3](要删除的元素)。它将返回[2,3,3] 我们可以假设给定的两个列表始终有效。 “要删除”列表中的元素将在原始列表中。
谢谢!
Is there a pythonic way to remove elements from one list to another list? (Not removing all duplicates)
For example, given [1, 2, 2, 3, 3, 3] (original list) and [1, 2, 3] (elements to be removed). It will return [2, 3, 3]
We can assume that the two given lists are always valid. Elements in the "to be removed" list will be in the original list.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个工作
This shoud work
我将使用要删除的元素的计数器。
因此,这样的
解决方案是线性时间 /空间。如果您实际上需要修改列表(IMO代码 - Smell,IMO),则需要二次时间
注意,请考虑您是否实际上只想要一个多键 - 即,您可以一直在使用计数器,请考虑:
I would use a counter of the elements to be removed.
So, something like
This solution is linear time / space. If you actually need to modify the list (which is code-smell, IMO), you would require quadratic time
Note, consider if you actually just want a multiset - i.e. you could just be working with counters all along, consider:
我不知道您对此操作解决了什么问题,因此不确定是否适用,但是如果您可以从原始列表中删除的元素(例如,从原始列表中获取随机子序列,然后减去它)然后,Pythonic,更有效的方法(如果您进行大量操作)将是使用可用对象的列表,而不是整数列表。这样一来,您就可以简单地做set1 -set2来实现目标:
它不会保留原始订单!但是您可以在最后对其进行排序。
I don't know what problem are you solving with this operation so not sure if this is applicable, but if you can take the elements you want to remove from the original list (for example get random subsequence from the original list and then subtract it) then pythonic and more efficient way (if you do a lot of this operation) would be to use list of hashable objects instead of a list of integers. That way you can do simply set1 - set2 to achieve the goal:
It won't preserve original order! But you can sort it at the end.