【问题标题】:Flutter/Dart: How to count tags of array of listFlutter/Dart:如何计算列表数组的标签
【发布时间】:2022-07-06 01:39:40
【问题描述】:

如何计算数组的标签? 我有这个代码:

class Product{
  Product({required this.name, required this.tags});
  final String name;
  final List<String> tags;

}

void TagList(){

  final product =[
    Product(name: 'bmw', tags: ['car', 'm3']),
    Product(name: 'kia', tags: ['car', 'morning', 'suv']),
    Product(name: 'hyundai', tags: ['car', 'ev6', 'suv']),
  ];
}

如何获取每个标签的使用次数?

预期输出:

汽车(3) 立方米(1) EV6(1) 越野车(2) 早上(1)

【问题讨论】:

    标签: dart collections


    【解决方案1】:

    试试这个方法,

    for(var i=0;i<product.length;i++){
    print("${product[i].name},(${product[i].tags.length})")
    }
    

    【讨论】:

    • 我认为你错过了理解 OP 的问题。措辞不好,你可以看看我的回答,看看 OP 是什么意思。
    【解决方案2】:

    您可以使用此函数循环遍历products 列表并获取每个tag 的使用次数:

    void printTags(List<Product> products) {
      final tagCount = <String, int>{};
      for (final product in products) {
        for (final tag in product.tags) {
          tagCount[tag] = tagCount.putIfAbsent(tag, () => 0) + 1;
        }
      }
      print(tagCount);
    }
    

    输出:

    {car: 3, m3: 1, morning: 1, suv: 2, ev6: 1}
    

    这是一个完整的可运行示例:

    void main() {
      final products = [
        Product(name: 'bmw', tags: ['car', 'm3']),
        Product(name: 'kia', tags: ['car', 'morning', 'suv']),
        Product(name: 'hyundai', tags: ['car', 'ev6', 'suv']),
      ];
    
      printTags(products);
    }
    
    class Product {
      Product({required this.name, required this.tags});
      final String name;
      final List<String> tags;
    }
    
    void printTags(List<Product> products) {
      final tagCount = <String, int>{};
      for (final product in products) {
        for (final tag in product.tags) {
          tagCount[tag] = tagCount.putIfAbsent(tag, () => 0) + 1;
        }
      }
      print(tagCount);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 2021-08-20
      • 1970-01-01
      • 2020-11-30
      • 2021-11-23
      相关资源
      最近更新 更多