2

I am trying to iterate over three lists at the same time and reference them in each iteration of the loop if that makes sense... however I can't find a simple way to do this...

For example

let list1 = [1,2,3,4];
let list2 = [2,4,3,1];
let list3 = [6,53,7,3];

for (x, y, z) in list1, list2, list3 {
   //do stuff
}

where x would refer to items in list1, y to list2, etc.

demstar16
  • 41
  • 3
  • Does this answer your question - https://stackoverflow.com/questions/29669287/how-can-i-zip-more-than-two-iterators – T. Kiley Mar 16 '22 at 08:23

2 Answers2

4

If you're using Rust 1.59 or higher, the following also works (without needing to depend on itertools):

use std::iter::zip;

fn main() {
  let list1 = [1,2,3,4];
  let list2 = [2,4,3,1];
  let list3 = [6,53,7,3];

  for (x, (y, z)) in zip(list1, zip(list2, list3)) {
    println!("{x}, {y}, {z}");
  }
}
cameron1024
  • 9,083
  • 2
  • 16
  • 36
1

Use itertools::izip:

use itertools::izip;

fn main() {
    let list1 = [1,2,3,4];
    let list2 = [2,4,3,1];
    let list3 = [6,53,7,3];

    for (x, y, z) in izip!(list1, list2, list3) {
       println!("{x}, {y}, {z}");
    }
}

Playground

Netwave
  • 40,134
  • 6
  • 50
  • 93