java - 从两个列表的组合中形成新的小列表
问题描述
我在一个大列表中有两种列表模式。
[[5.35, 5.09, 4.95, 4.81, 4.75, 5.19], [3601.0, 3602.0, 3603.0, 3600.0, 3610.0, 3600.0],[..,..,..,],[..,..,..],...]
简单地说,它是一个组合
[ [pricesList1],[DurationList1],[PricesList2],[DurationList2],...]
我现在想创建一个新列表,其中包含两个列表中的价格和相应的持续时间作为每组中的一对。例如 :
[[[5.35,3601.0],[5.09,3602.0],[4.95,3603],[4.81,3600],[4.75,3610],....],[[p1,d1],[p2,d2],[p3,d3],..],[[],[],[],..],....]
我试过使用List<List<Object>>
and List<List<String>>
。但是没有用。我怎样才能做到这一点?
我编程如下,这是错误的:
List<List<Object>> DurationList = new ArrayList<List<Object>>();
List<List<Object>> FinalList = new ArrayList<List<Object>>();
List<List<String>> SlotList = null;
for(int pair=0; pair<(FinalList.size()-1) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList = new ArrayList<List<String>>();
SlotList.addAll((Collection<? extends List<String>>) (FinalList.get(pair).get(innerloop)));
}
}
for(int pair=1; pair<(FinalList.size()) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList.addAll((Collection<? extends List<Object>>) FinalList.get(pair).get(innerloop));
}
}
解决方案
假设输入列表总是有偶数个子列表并且子列表对具有相同的大小,您可以使用一个for
循环遍历外部列表的元素两两:
List<List<String>> result = new ArrayList<>();
for (int i=0; i<outerList.size(); i+=2) {
List<String> priceList = outerList.get(i);
List<String> durationsList = outerList.get(i+1);
for (int j=0; j<priceList.size(); j++) {
List<String> newEntry = new ArrayList<>();
newEntry.add(priceList.get(j));
newEntry.add(durationsList.get(j));
result.add(newEntry);
}
}
正如评论的那样,我建议定义您自己的类来存储价格和持续时间,而不是使用它List<String> newEntry
。
推荐阅读
- python - 如何在 NLP 中使用 python 使用 .any() 或 a.all()?
- python - 将配对列表值转换为字典
- spring - 新创建/扩展的 JHipster 端点不起作用(404 错误)
- ruby-on-rails - Milia gem Rails 6
- c++ - 取消引用指针列表的迭代器
- .htaccess - 避免在 contao 中进行多次重定向
- javascript - 我应该将这些奇怪的文件放在 Flask 应用程序的文件结构中的什么位置?
- python - 将相同/父目录中的文件导入 python 文件以作为 pypi 包上传
- javascript - appendChild 仅在 settimeout 内时起作用
- python - 用最后一个已知值替换 NaN