【问题标题】:Jmeter Groovy creating new list by iterting from previous listJmeter Groovy 通过从前一个列表迭代创建新列表
【发布时间】:2018-08-18 15:43:39
【问题描述】:

我有一个动态的列表 (tsts),它是在分离操作中派生的,但可以如下所示。 我想遍历 tsts 并创建一个新列表 --> list1,只提取到索引 2。我已经尝试了 for 循环,甚至 --> tsts.eachWithIndex { item, index -> for some为什么我的 list1 只包含最后一项?

import org.apache.jmeter.util.JMeterUtils;
import groovy.json.JsonSlurper;
def jsonResponse = null;
List<String> tsts = new ArrayList<String>()
tsts = [10, 11, 12];
str1 = "abc"

def map1 = [:]
def list1 = []
int TCcntr = 2;
cnt1 = 0
System.out.println("1 My Loop begins----------------");
for(int i = 0;i<TCcntr;i++) {
    map1.clear()
    map1.put(str1,tsts[cnt1].toInteger());
    System.out.println("map1----> "+map1);
    // list1.add(map1);
    list1 = list1+map1;
    System.out.println("list---> "+list1);
    cnt1 = cnt1+1;
}

我的输出

1 My Loop begins----------------
map1----> [abc:10]
list---> [[abc:10]]
map1----> [abc:11]
list---> [[abc:11], [abc:11]]

为什么列表 1 一直在获取最后一个项目迭代?它应该是这样的

   list1----> [[abc:10], [abc:11]]

【问题讨论】:

  • 因为list1 = list1+map1。您正在 for 内的该列表中累积。这段代码看起来非常复杂 TBH。我猜def list1 = tsts.collect{ [abc: it ] } 就足够了。
  • 谢谢,但我只想用我刚刚尝试过的代码索引 1:[[abc:10], [abc:11], [abc:12]] 我喜欢索引 1 或 --> [[abc:10], [abc:11]]
  • 然后使用tsts.take(2).collect{ [abc: it ] }
  • 谢谢我现在得到前 2 个,如果我想说从索引 1 到 2 我该如何索引?使用 for 循环,您可以轻松选择所需的索引并创建新列表。 take(2) 只选择前 2 个。
  • 那么您可以使用tail()drop(1) 代替take(2)

标签: groovy jmeter


【解决方案1】:

这很有效,感谢 Dimitri 和 Tim,我还学习了其他方法

tsts = [10, 11, 12, 13];
str1 = "abc"
def list1 = []
int TCcntr = 3;

for(int i = 1;i<TCcntr;i++) {
    map1 =[:]
    map1.put(str1,tsts[i].toInteger());
    list1 = list1+map1;
}

输出

 list---> [[abc:11], [abc:12]]

【讨论】:

  • def list1 = tsts.drop(1).take(2)*.toInteger().collect{ [abc: it] }
  • 哇这个真的很棒,我喜欢它,它和其他人一样优雅,完全符合我的要求
猜你喜欢
  • 2017-03-25
  • 1970-01-01
  • 2020-10-20
  • 2021-12-11
  • 2014-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-03
相关资源
最近更新 更多