简体   繁体   中英

How to convert a Vec<Vec<f64>> into a string

I am new to Rust, and I am struggling with a simple task. I'd like to convert a matrix into a string, with the fields separated by tabs. I think this is possible by using the map function or something similar, but right now whatever I try gives me an error.

This is what I have, and I'd like to convert the col part into function, which returns a tab separated string, which I can print. In Python this is something like row.join("\\t") . Is there something similar in Rust?

fn print_matrix(vec: &Vec<Vec<f64>>) {
    for row in vec.iter() {
        for col in row.iter() {
           print!("\t{:?}",col);
        }
        println!("\n");
    }
}

There is indeed a join in the standard library, but it's not super useful (often additional allocation is required). But you can see a solution here:

fn print_matrix(vec: &Vec<Vec<f64>>) {
    for row in vec {
        let cols_str: Vec<_> = row.iter().map(ToString::to_string).collect();
        let line = cols_str.join("\t");
        println!("{}", line);
    }
}

The problem is that this join works with slices and not with iterators. We have to convert all elements into a string first, collect the result in a new vector and can use join then.

The crate itertools defines a join method for iterators and can be applied like so:

for row in vec {
    let line = row.iter().join("\t");
    println!("{}", line);
}

And to avoid using any of the named functionality, you can of course do it manually:

for row in vec {
    if let Some(first) = row.get(0) {
        print!("{}", first);            
    }
    for col in row.iter().skip(1) {
        print!("\t{}", col);
    }
    println!("");
}

除了从itertools join你总是可以在迭代器上使用fold (这非常有用),如下所示:

row.iter().fold("", |tab, col| { print!("{}{:?}", tab, col); "\t" });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM