Reputation: 3501
I have a vector of tuples:
let v = vec![(1, 1), (1, 1), (1, 3), (1, 4), (2, 2), (2, 4), (2, 6)];
and I would like to split it into two lists. The first list containing the first element from each of the tuples and the second containing the second one, i.e.:
l1 = [1, 1, 1, 1, 2, 2]
and l2 = [1, 1, 3, 4, 2, 4]
.
How can I do this?
Upvotes: 8
Views: 2763
Reputation: 36536
@Alexey Larionov's answer is perfect, but if you were looking for a more manual approach, it's still quite reasonable given Rust's ability to pattern match.
fn main() {
let v = vec![(1, 1), (1, 1), (1, 3), (1, 4), (2, 2), (2, 4), (2, 6)];
let mut v1: Vec<i32> = vec![];
let mut v2: Vec<i32> = vec![];
for (first, second) in v {
v1.push(first);
v2.push(second);
}
println!("{:?}", v1);
println!("{:?}", v2);
}
Upvotes: 2
Reputation: 7927
Iterator.unzip()
is specifically created for this. Playground
fn main() {
let v = vec![(1, 1), (1, 1), (1, 3), (1, 4), (2, 2), (2, 4), (2, 6)];
let (v1, v2): (Vec<_>, Vec<_>) = v.into_iter().unzip();
println!("{:?}", v1);
println!("{:?}", v2);
// [1, 1, 1, 1, 2, 2, 2]
// [1, 1, 3, 4, 2, 4, 6]
}
Upvotes: 10