首页 > 解决方案 > 摆脱 Scala 列表中的迭代器

问题描述

当前情况: 我正在使用组合方法来创建列表元素的所有可能组合。

//Input list
lf  : List[(Char, Int)] = List((a,2), (a,1), (b,2), (b,1))
//For loop
for (len <- (0 to lf.length).toList) yield {lf.combinations(len)}
//> res1: List[Iterator[List[(Char, Int)]]] = List(non-empty iterator, non-empty
//|  iterator, non-empty iterator, empty iterator, empty iterator)

组合返回Iterator[List[A]]

我需要的

  1. 项目清单List[List[(Char, Int)]]
  2. 忽略空迭代器

我怎样才能摆脱迭代器?

标签: scalaiterator

解决方案


获取所有combinations(),从单个元素到完整的List,在一个List.

lf.indices.flatMap(x => lf.combinations(x+1)).toList
//res0: List[List[(Char, Int)]] = List(
//   List((a,2)), List((a,1)), List((b,2)), List((b,1))
// , List((a,2), (a,1)), List((a,2), (b,2)), List((a,2), (b,1)), List((a,1), (b,2)), List((a,1), (b,1)), List((b,2), (b,1))
// , List((a,2), (a,1), (b,2)), List((a,2), (a,1), (b,1)), List((a,2), (b,2), (b,1)), List((a,1), (b,2), (b,1))
// , List((a,2), (a,1), (b,2), (b,1)))

推荐阅读