Is there a standard library functions to zip two finite iterators and pad the shorter one.
For example given the following two iterators:
1->2->3
1->2->3->4->5
I would like to get:
(1,1)->(2,2)->(3,3)->(0,4)->(0,5)
Is there a standard library functions to zip two finite iterators and pad the shorter one.
For example given the following two iterators:
1->2->3
1->2->3->4->5
I would like to get:
(1,1)->(2,2)->(3,3)->(0,4)->(0,5)
You need itertools for this
itertools
is the way to go, but one can easily concoct this with a few lines of code. A naive example:
let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3, 4, 5];
let max_len = v1.len().max(v2.len());
let v1 = v1
.into_iter()
.chain(std::iter::repeat(Default::default()))
.take(max_len);
let v2 = v2
.into_iter()
.chain(std::iter::repeat(Default::default()))
.take(max_len);
let zipped = v1.zip(v2);
Put some of this in a helper fn or macro, and you're all set
That's a clean solution. I didn't think of using chain
and take
that way.
Thank you all
You could move the take(max_len)
to zipped, e.g. let zipped = v1.zip(v2).take(max_len)
which makes it more obvious and less error prone (DRY)