关于向量:如何将 Vec<Vec> 转换为字符串 | 珊瑚贝

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


我是 Rust 的新手,我正在为一项简单的任务而苦苦挣扎。我想将矩阵转换为字符串,字段由制表符分隔。我认为这可以通过使用 map 函数或类似的东西来实现,但现在无论我尝试什么都会给我一个错误。

这就是我所拥有的,我想将 col 部分转换为函数,它返回一个制表符分隔的字符串,我可以打印它。
在 Python 中,这类似于 row.join(“\\t”)。 Rust 中是否有类似的东西?

1
2
3
4
5
6
7
8
9
fn print_matrix(vec: &Vec<Vec<f64>>) {
    for row in vec.iter() {
        for col in row.iter() {
           print!(“\\t{:?}”,col);
        }
        println!(“\
“);
    }
}
  • 这其中的哪一部分不起作用?你能提供一个关于 Playpen 的最小的、完整的例子吗?这段代码似乎没有任何问题。
  • 它应该打印 string<tab>string<tab>string 但它会打印一个前导选项卡。必须有比这更优雅的解决方案,无需摆弄
  • 查看 doc.rust-lang.org/std/fmt/#format_args 下的示例


标准库中确实有一个join,但它不是超级有用(通常需要额外分配)。但是你可以在这里看到一个解决方案:

1
2
3
4
5
6
7
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);
    }
}

问题是这个 join 与切片而不是迭代器一起工作。我们必须先将所有元素转换为字符串,然后将结果收集到一个新向量中,然后才能使用 join。

板条箱 itertools 为迭代器定义了一个 join 方法,可以像这样应用:

1
2
3
4
for row in vec {
    let line = row.iter().join(“\\t”);
    println!(“{}”, line);
}

为了避免使用任何命名的功能,您当然可以手动操作:

1
2
3
4
5
6
7
8
9
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 (这真的很有用),像这样:

1
row.iter().fold(“”, |tab, col| { print!(“{}{:?}”, tab, col);”\\t” });
  • 这将以一个额外的 \\t 结束


来源:https://www.codenong.com/36111784/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8903.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?