English 中文(简体)
• 如何用“uniq-c'一种分类标签,以伪造和篡改计数和价值
原标题:How to `uniq -c` a sorted vec in rust and iterate the count and value
  • 时间:2023-12-14 01:51:14
  •  标签:
  • rust

下面是伪装法,当然是按预期的。 我想利用一个召集人对每个要素和发生次数进行分类。

fn main() {
  let a = vec![1,1,2,3,3,3];
  
  for (value, count) in a.iter1(){
      println!("{value}	{count}")  
      // 1, 2
      // 2, 1
      // 3, 3
  }
  
    for (value, count) in a.iter2().rev(){
      println!("{value}	{count}")  
      // 3, 3
      // 2, 1
      // 1, 2
  }
}
问题回答

您可使用group_by itertools。 与<代码>uniq - c类似,它只能将连续要素组合在一起。

use itertools::Itertools;

fn main() {
    let a = vec![1, 1, 2, 3, 3, 3];

    for (value, group) in &a.iter().group_by(|&&x| x) {
        let count = group.count();
        println!("{value}	{count}")
        // 1, 2
        // 2, 1
        // 3, 3
    }
    
    println!("---");

    for (value, group) in &a.iter().rev().group_by(|&&x| x) {
        let count = group.count();
        println!("{value}	{count}")
        // 3, 3
        // 2, 1
        // 1, 2
    }
}




相关问题
Creating an alias for a variable

I have the following code in Rust (which will not compile but illustrates what I am after). For readability purposes, I would like to refer the same string with two different names so that the name of ...

Rust Visual Studio Code code completion not working

I m trying to learn Rust and installed the Rust extension for VSCode. But I m not seeing auto-completions for any syntax. I d like to call .trim() on String but I get no completion for it. I read that ...

热门标签