英文:
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
我的当前最佳解决方案是:
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<u8> into a Vec<(u8, u8, u8)> 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<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]));
}
答案1
得分: 0
Itertools 提供了一个 tuples()
适配器,它将连续的项分组成元组。
另外,标准库也有 slice::chunks
和 slice::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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论