Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir how to iterate over two lists at once to produce a new list?

I'd like to iterate over two lists at once, but can't figure out how. The for loop, which allows you to have multiple lists acts as nested for loops and I'm not that familiar with Enum, but perhaps there's a solution there.

Python has zip(list_1,list_2) and enumerate(list_1) to accomplish this

In Tcl is even easier for me:

% foreach var1 [list 1 3] var2 [list 2 4] {
    puts "$var1 $var2"
  }
1 2
3 4

But I cannot figure out how to do it in Elixir.

The reason I want to do it is because I have a list of maps like this

[%{"a" => "1539", "b" => "300"},
 %{"a" => "4095", "b" => "0"},
 %{"a" => "5371", "b" => "0"},
 %{"a" => "7524", "b" => "0"},
 %{"a" => "8267", "b" => "27"}]

and I have a list of items of the same size:

["a","b","c","d","e"]

and I'd like to run them through a loop together to replace items in the map if and when one of the elements in the map is a certain condition (not 0):

[%{"a" => "a", "b" => "300"},   # notice the change in element "a"
 %{"a" => "4095", "b" => "0"},
 %{"a" => "5371", "b" => "0"},
 %{"a" => "7524", "b" => "0"},
 %{"a" => "e", "b" => "27"}]    # notice the change in element "a"

Anyway. Can someone help me understand enumerable or how to iterate over two lists in elixir?

like image 935
Legit Stack Avatar asked Oct 25 '25 05:10

Legit Stack


2 Answers

You can use Enum.zip/2 and Enum.map/2 in Elixir to do accomplish the same thing:

list_of_maps
|> Enum.zip(list_of_items)
|> Enum.map(fn {map, item} -> 
   if (map["b"] == "0"), do: map, else: Map.put(map, "a", item)
end)
like image 121
Sheharyar Avatar answered Oct 26 '25 21:10

Sheharyar


Or, using the comprehension:

for {map, item} <- Enum.zip(list_of_maps, list_of_items),
  into: [],
    do: if (map["b"] == "0"), do: map, else: %{map | "a" => item}
like image 23
Aleksei Matiushkin Avatar answered Oct 26 '25 22:10

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!