You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Karate中如何基于动态列表遍历统计另一列表元素出现次数

在Karate框架中批量统计列表元素出现次数

方法一:遍历list2逐个统计

直接遍历list2的每个元素,复用你已掌握的karate.filter方法统计其在list1中的出现次数,最终将结果存入对象:

* def list1 = ["ART - Run and Support","ART - Run and Support","Clt group","Clt group"]
* def list2 = ["ART - Run and Support","Clt group"]

// 初始化空对象存储统计结果
* def countResult = {}

// 遍历list2的每个元素
* karate.forEach(list2, function(item) {
    // 定义匹配当前元素的过滤函数
    * def matchFn = function(x) { return x == item }
    // 统计数量并写入结果对象
    * countResult[item] = karate.filter(list1, matchFn).length
})

// 输出统计结果,格式为 {"ART - Run and Support":2, "Clt group":2}
* print countResult

方法二:预统计list1再提取目标元素(高效版)

先通过reduce函数一次性统计list1中所有元素的出现次数,再遍历list2提取对应结果,适合数据量较大的场景:

* def list1 = ["ART - Run and Support","ART - Run and Support","Clt group","Clt group"]
* def list2 = ["ART - Run and Support","Clt group"]

// 预统计list1所有元素的出现次数
* def fullCountMap = list1.reduce(function(acc, current) {
    acc[current] = (acc[current] || 0) + 1
    return acc
}, {})

// 提取list2中元素的统计结果
* def targetCounts = {}
* karate.forEach(list2, function(item) {
    targetCounts[item] = fullCountMap[item] || 0
})

// 输出结果
* print targetCounts

两种方法最终都会得到你需要的统计结果,第二种方法只需遍历list1一次,性能更优。

内容的提问来源于stack exchange,提问作者user20485356

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:25:48