简体   繁体   English

Elixir中的红宝石和操作员是什么?

[英]What's the ruby & operator in Elixir?

like this: 像这样:

list1 = [1,2,3,4,5]  
list2 = [2,3,6]  
list1 & list2 = [2,3]

I need to find the repeat list ie common items in list1 and list2 . 我需要找到重复列表,即list1list2常用项。

The function you are looking for is Set.intersection/2 : 您正在寻找的功能是Set.intersection / 2

iex> Set.intersection(Enum.into([1, 2, 3 ,4 ,5], HashSet.new), Enum.into([2, 3, 6], HashSet.new))
[2, 3]

Please note that the conversion to a set means that duplicates are not permitted: 请注意,转换为集合意味着不允许重复:

Enum.into([1, 2, 3 ,2 ,5, 3], HashSet.new)
HashSet<[2, 3, 1, 5]>

Also note that order is not maintained: 另请注意,订单未得到维护:

iex>Enum.into([1, 2, 3 ,4 ,5, 6], HashSet.new) |> Set.to_list
[2, 6, 3, 4, 1, 5]

Not sure if elixir has a similar & operator for list s. 不确定elixir是否有与list s类似的&运算符。

But, you can achive your desried result by using the -- operator twice: 但是,你可以使用--运算符两次来实现你的结果:

iex> list1
# => [1, 2, 3, 4, 5]
iex> list2
# => [2, 3, 6]
iex> list3 = list1 -- list2
# => [1, 4, 5]   
iex> final_list = list1 -- list3
# => [2, 3] # this is your desired result

You can do it in one line too: 你也可以在一行中完成:

iex> list1 -- (list1 -- list2)
# => [2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM