How can I convert a vector into a vector with every x elements grouped into a tuple? E.g. Vec<u8> -> Vec<(u8, u8, u8)>

huangapple go评论55阅读模式
英文:

How can I convert a vector into a vector with every x elements grouped into a tuple? E.g. Vec<u8> -> Vec<(u8, u8, u8)>

问题

我正在尝试将一个Vec转换为Vec<(u8, u8, u8)>,将相邻元素分组,并想知道是否有一种快速的方法,因为迭代大图像可能会很慢。

我的当前最佳解决方案是:

let dimensions = (img.dimensions().0 as usize, img.dimensions().1 as usize);
let size = dimensions.0 * dimensions.1;
let raw_data: Vec<u8> = img.into_raw();
let mut data: Vec<(u8, u8, u8)> = Vec::with_capacity(size);

for i in 0..size {
    data.push((raw_data[i*3], raw_data[i*3+1], raw_data[i*3+2]));
}
英文:

I am trying to convert a Vec&lt;u8&gt; into a Vec&lt;(u8, u8, u8)&gt; grouping adjacent elements and want to know if there is a quick way of doing this as iteration for a large image could be quite slow.

My current best solution is:

let dimensions = (img.dimensions().0 as usize, img.dimensions().1 as usize);
let size = dimensions.0 * dimensions.1;
let raw_data: Vec&lt;u8&gt; = img.into_raw();
let mut data: Vec&lt;(u8, u8, u8)&gt; = Vec::with_capacity(size);

for i in 0..size {
    data.push((raw_data[i*3], raw_data[i*3+1], raw_data[i*3+2]));
}

答案1

得分: 0

Itertools 提供了一个 tuples() 适配器,它将连续的项分组成元组。

另外,标准库也有 slice::chunksslice::chunks_exact,它们的功能略有限制。它们需要一个切片输入(或者类似于切片的解引用到切片的东西,比如 vec),并且你会失去类型安全性方面的优势(因为它们返回的是可能小于 chunks 指定大小的切片),但它们不需要额外的依赖。

英文:

Itertools has a tuples() adapter which groups consecutive items by tuples.

Alternatively and a bit more limited, the standard library has slice::chunks and slice::chunks_exact. That needs a slice input (or something which derefs to a slice, like a vec) and you lose the type-safety aspects (as they return slices, possibly smaller than specified for chunks) but they don't require a dependency.

huangapple
  • 本文由 发表于 2023年2月16日 19:43:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定