如何在没有列表 2 元素的情况下过滤列表 1
How to filter list 1 without elements of list 2
基于 List1
创建一个没有 List2
元素的新列表的最佳方法是什么?
List1 = ["Candy", "Brandy", "Sandy", "Lady", "Baby", "Shady"].
List2 = ["Sandy", "Shady", "Candy", "Sandy"].
新列表的内容应该是:
List3 = ["Brandy", "Lady", "Baby"].
目前,最好的方法是使用处理集合的模块,例如 ordsets:
> ordsets:subtract(ordsets:from_list(List1), ordsets:from_list(List2)).
["Baby","Brandy","Lady"]
如果您使用 Erlang/OTP 22 或更高版本(将于 2019 年 6 月发布),最好的方法是使用 --
运算符:
> List3 = List1 -- List2.
["Brandy","Lady","Baby"]
这个操作的运行时复杂度是 O(n log n) 从 Erlang/OTP 22 开始,但是在早期的 Erlang 版本中,这个操作的运行时复杂度是 O(n*m),所以它会如果两个列表都很长,性能会很差。
参见the Retired Myths chapter in the Erlang Efficiency Guide:
12.3 Myth: List subtraction ("--" operator) is slow
List subtraction used to have a run-time complexity proportional to the product of the length of its operands, so it was extremely slow when both lists were long.
As of OTP 22 the run-time complexity is "n log n" and the operation will complete quickly even when both lists are very long. In fact, it is faster and uses less memory than the commonly used workaround to convert both lists to ordered sets before subtracting them with ordsets:subtract/2
.
基于 List1
创建一个没有 List2
元素的新列表的最佳方法是什么?
List1 = ["Candy", "Brandy", "Sandy", "Lady", "Baby", "Shady"].
List2 = ["Sandy", "Shady", "Candy", "Sandy"].
新列表的内容应该是:
List3 = ["Brandy", "Lady", "Baby"].
目前,最好的方法是使用处理集合的模块,例如 ordsets:
> ordsets:subtract(ordsets:from_list(List1), ordsets:from_list(List2)).
["Baby","Brandy","Lady"]
如果您使用 Erlang/OTP 22 或更高版本(将于 2019 年 6 月发布),最好的方法是使用 --
运算符:
> List3 = List1 -- List2.
["Brandy","Lady","Baby"]
这个操作的运行时复杂度是 O(n log n) 从 Erlang/OTP 22 开始,但是在早期的 Erlang 版本中,这个操作的运行时复杂度是 O(n*m),所以它会如果两个列表都很长,性能会很差。
参见the Retired Myths chapter in the Erlang Efficiency Guide:
12.3 Myth: List subtraction ("--" operator) is slow
List subtraction used to have a run-time complexity proportional to the product of the length of its operands, so it was extremely slow when both lists were long.
As of OTP 22 the run-time complexity is "n log n" and the operation will complete quickly even when both lists are very long. In fact, it is faster and uses less memory than the commonly used workaround to convert both lists to ordered sets before subtracting them with
ordsets:subtract/2
.