最好的方法是什么? 我有两个清单:
val l1 = List("a", "b")
val l2 = List(1, 2)
我想生成这个:
List (
List(('a', 1), ('b', 1)),
List(('a', 1), ('b', 2)),
List(('a', 2), ('b', 1)),
List(('a', 2), ('b', 2))
)
这基本上是第一个与第二个列表组合创建元组列表的列表? 考虑使用带滑动(2,2)的foldLeft来获得我的结果,但不能得到正确的结果。
解决方案应该适用于任何尺寸和类型,例如列表(' a',''' c')和列表(" 1"," 2")
由于
答案 0 :(得分:14)
List.fill
,combinations
和permutations
的组合来完成(我很难相信那里这样做并不容易,但我还没有找到任何方法:
def prod[T](lst: List[T], n: Int) = List.fill(n)(lst).flatten.combinations(n).flatMap(_.permutations)
n
的值由列表l1
的大小决定。在您的示例prod(l2, 2)
中,我们会List(List(1, 1), List(1, 2), List(2, 1), List(2, 2))
。其余的只是map
和zip
的应用。我们一起
prod(l2, l1.size).map(l1.zip(_))
l1 = List('a', 'b', 'c'), l2 = List("1", "2")
的输出:
List((a,1), (b,1), (c,1))
List((a,1), (b,1), (c,2))
List((a,1), (b,2), (c,1))
List((a,2), (b,1), (c,1))
List((a,1), (b,2), (c,2))
List((a,2), (b,1), (c,2))
List((a,2), (b,2), (c,1))
List((a,2), (b,2), (c,2))
答案 1 :(得分:-1)
最好的方法是使用a进行理解。比公认的IMO解决方案干净得多:)
for {
i1 <- List('a', 'b', 'c')
i2 <- List(1, 2)
} yield List(i1, i2)