且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从列表元素创建所有可能的组合?

更新时间:2023-02-10 07:42:11

或者您可以使用子集方法。不过,您必须先将列表转换为集合。

  scala> List(1,2,3).toSet [Int] .subsets.map(_ .toList).toList 
res9:List [List [Int]] = List(List(),List(1),List (2),清单(3),清单(1,2),清单(1,3),清单(2,3),清单(1,2,3))


I have the following list:

List(a, b, c, d, e)

How to create all possible combinations from the above list?

I expect something like:

a
ab
abc 

Or you could use the subsets method. You'll have to convert your list to a set first though.

scala> List(1,2,3).toSet[Int].subsets.map(_.toList).toList
res9: List[List[Int]] = List(List(), List(1), List(2), List(3), List(1, 2), List(1, 3), List(2, 3), List(1, 2, 3))