在Scala中的列表中摆脱Iterator

时间:2018-11-28 08:38:45

标签: scala iterator

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

//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. 忽略空的迭代器

如何摆脱Iterator?

2 个答案:

答案 0 :(得分:2)

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)))

答案 1 :(得分:-1)

您可以使用.toList

val lf  : List[(Char, Int)] = List(('a',2), ('a',1), ('b',2), ('b',1))

for (len <- (0 to lf.length).toList) yield {lf.combinations(len)}.filter(_.length > 0).toList
相关问题