如何在列表的每个元素之间插入值?

man*_*dez 5 arrays list rust

这个(游乐场):

let s = "Hello world!";
let splitted_string = s.split_terminator("").skip(1).collect::<Vec<&str>>();
println!("splitted_string: {:?}", splitted_string);
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

splitted_string: ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]
Run Code Online (Sandbox Code Playgroud)

如何a在每个元素之间插入一个并获得这样的东西?

["H", "a", "e", "a", "l", "a", "l", "a", "o", "a", " ", "a", "w", "a", "o", "a", "r", "a", "l", "a", "d", "a", "!"]
Run Code Online (Sandbox Code Playgroud)

Tod*_*odd 6

已经有了一个很好的.flat_map()答案,但是为了多样化而给出稍微不同的方法,我们可以使用以下方法从末尾删除多余的“a” .take()

fn main() {
    let s = "Hello world!";
    
    let interspersed = s.chars()
                        .flat_map(|c| [c, 'a'])
                        .take(s.chars().count() * 2 - 1)
                        .collect::<String>();
                        
    println!("interspersed: {:?}", interspersed);
}
Run Code Online (Sandbox Code Playgroud)

输出:

interspersed: "Haealalaoa awaoaralada!"
Run Code Online (Sandbox Code Playgroud)

我已经更新了答案,以解决字符串中的字节数与应用s.chars().count()而不是 的字节数不匹配的情况s.len()。注意这s.chars().count()是一个O(n)操作。


Net*_*ave 5

它仍处于实验阶段,但iter::intersperse确实做到了这一点。

从文档示例

#![feature(iter_intersperse)]

let mut a = [0, 1, 2].iter().intersperse(&100);
assert_eq!(a.next(), Some(&0));   // The first element from `a`.
assert_eq!(a.next(), Some(&100)); // The separator.
assert_eq!(a.next(), Some(&1));   // The next element from `a`.
assert_eq!(a.next(), Some(&100)); // The separator.
assert_eq!(a.next(), Some(&2));   // The last element from `a`.
assert_eq!(a.next(), None);
Run Code Online (Sandbox Code Playgroud)

同时,itertools::intersperse板条箱也具有相同的功能。

仅使用当前稳定标准库的解决方案:

use std::iter;
fn main() {
    let s = "Hello world!";
    let result: Vec<char> = s
        .chars()
        .zip(iter::repeat('a'))
        .flat_map(|(a, sep)| vec![sep, a])
        .skip(1)
        .collect();
    println!("{:?}", result);
}
Run Code Online (Sandbox Code Playgroud)

结果:

['H', 'a', 'e', 'a', 'l', 'a', 'l', 'a', 'o', 'a', ' ', 'a', 'w', 'a', 'o', 'a', 'r', 'a', 'l', 'a', 'd', 'a', '!']
Run Code Online (Sandbox Code Playgroud)

操场