【问题标题】:Printing the most frequent value in a text打印文本中出现频率最高的值
【发布时间】:2021-08-17 11:53:24
【问题描述】:

假设我有一个字符串列表。

我看到了代码:How to count items' occurence in a List

我想在我的小部件中将最常见的字符串打印为文本。我如何运行它并在那里打印?

我是否使用 void main() ?

class user with ChangeNotifier {
  static String topWord;

  notifyListeners();
}

void countWord() {
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
  var popular = Map();

  elements.forEach((element) {
    if(!popular.containsKey(element)) {
      popular[element] = 1;
    } else {
      popular[element] +=1;
    }
  });

  print(popular);
return user.topWord = popular; 
}

附上我返回结果时的一些截图

【问题讨论】:

  • 创建一个新函数并将代码粘贴到其中并在函数类型的末尾return map 现在您可以使用返回的值在您的小部件中打印。
  • @ChiragBargoojar 看看编辑后的 ​​Chirag 代码

标签: list flutter dart


【解决方案1】:

在这里,您可以先创建计数值的映射,然后使用该映射可以获得键的最大值。

来源Here

class HomePage extends StatelessWidget {
  String email;
  var maxocc = maxOccurance();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("App Bar"),
      ),
      body: Center(
        child: Container(
          child: Text(maxocc),
        ),
      ),
    );
  }
}

String maxOccurance() {
  var elements = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "a",
    "b",
    "c",
    "f",
    "g",
    "h",
    "h",
    "h",
    "e"
  ];

  // Here creating map of all values and counting it
  final folded = elements.fold({}, (acc, curr) {
    acc[curr] = (acc[curr] ?? 0) + 1;
    return acc;
  }) as Map<dynamic, dynamic>;
  print(folded);

  // Here getting maximum value inside map
  final sortedKeys = folded.keys.toList()
    ..sort((a, b) => folded[b].compareTo(folded[a]));

  return "${sortedKeys.first} occurs maximun times i.e. ${folded[sortedKeys.first]}";
}

在这里输出

【讨论】:

    猜你喜欢
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多