【发布时间】: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)