当前情况: 我正在使用组合方法来创建列表元素的所有可能组合。
//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]]
我需要的
List[List[(Char, Int)]]
如何摆脱Iterator?
答案 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