我有一种情况,如果字符串列表中的字符串与整数列表中的索引匹配(基于字符串列表生成),我想执行操作
下面是一些伪代码,试图阐明我要实现的目标。
List<int> wordIndex = [1,3,5];
List<String> wordList = ['this', 'is','a', 'test', 'a'];
//Pseudo code
wordList.forEach(word)) {
if (wordIndex item matches index of word) {
do something;
} else {
od something else;
}
}
这是我遇到问题的
if (wordIndex item matches index of word)
,不胜感激任何想法。
最佳答案
如果我对您的理解正确,那么您想知道wordIndex
列表中是否包含单词的索引,即要获取所有wordList
项,并将其索引存储在wordIndex
中。
有两种解决方法:
使用 Iterable.contains
在这种情况下,我们可以简单地检查wordIndex
列表中是否存在当前索引。
for (var index = 0; index < wordList.length; index++) {
if (wordIndex.contains(index)) {
// do something
return;
}
// do something else
}
遍历
wordIndex
如果您只对匹配项感兴趣,则此方法更合理。
在这里,我们遍历索引列表,然后简单地在
wordList
中获取匹配的元素。但是,您将无法对不匹配的商品采取措施:for (final index in wordIndex) {
final word = wordList[index];
// do something
}
关于loops - 获取循环中的项目索引以与存储的索引匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61431937/