Hi everyone, I've decided to stop banging my head against the wall on this one.
I'm trying to use the group_by
method from itertools
. I thought I understood how it works, but I must be doing something wrong...
I'm iterating over some data on the form of ((x: i32, y: i32), z: i32)
, and I'd like to use group_by
on the z
element. This is where it all falls apart. Sometimes, the output is correctly grouped, but sometimes elements with the same key value end up in different groups. If you take a look at the output below you'll understand. Try running the snippet a few times in the Playground. I'm guessing you'll get various results.
So my question is: What am I doing wrong?
Edit: Reading through the docs it seems like the magic words are consecutive elements.
use std::collections::HashSet;
use itertools::Itertools;
fn main() {
let s = vec![((0, 1), 1), ((0, 2), 2), ((1, 2), 2), ((3, 1), 1)].into_iter().collect::<HashSet<_>>();
println!("{:?}\n", s);
s.iter()
.group_by(|&x| x.1)
.into_iter()
.map(|(k, r)| (k, r.collect::<Vec<_>>()))
.for_each(|x| println!("Key: {:?} | Group: {:?}", x.0, x.1));
}
Output:
{((3, 1), 1), ((0, 2), 2), ((0, 1), 1), ((1, 2), 2)}
Key: 1 | Group: [((3, 1), 1)]
Key: 2 | Group: [((0, 2), 2)]
Key: 1 | Group: [((0, 1), 1)]
Key: 2 | Group: [((1, 2), 2)]
Errors:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.31s
Running `target/debug/playground`