【问题标题】:How to make column pairs of map?如何制作地图的列对?
【发布时间】:2014-04-03 07:52:47
【问题描述】:

我有一些类似的专栏

age | company | country | gender |
----------------------------------
 1  |   1     |  1      |  1     |
-----------------------------------

我想创建像

这样的配对
  • (年龄,公司)
  • (公司、国家)
  • (国家、性别)
  • (公司、性别)
  • (年龄、性别)
  • (年龄、国家)
  • (年龄、公司、国家)
  • (公司、国家、性别)
  • (年龄、国家、性别)
  • (年龄、公司、性别)
  • (年龄、公司、国家、性别)

【问题讨论】:

  • 我想创建这些对,因为我还有一些其他两列、三列和四列的表。我想制作这些对,并根据列对将这些对的值插入表中。
  • 以map的形式在controller中。

标签: scala playframework-2.0


【解决方案1】:

使用Set 集合方法subsets 生成powerset 的惯用方法,

implicit class groupCols[A](val cols: List[A]) extends AnyVal {
  def grouping() = cols.toSet.subsets.filter { _.size > 1 }.toList
}

然后

List("age","company","country","gender").grouping

交付

List( Set(age, company), 
      Set(age, country), 
      Set(age, gender), 
      Set(company, country), 
      Set(company, gender), 
      Set(country, gender), 
      Set(age, company, country), 
      Set(age, company, gender), 
      Set(age, country, gender), 
      Set(company, country, gender), 
      Set(age, company, country, gender))

注意,幂集包括空集和原始集中每个元素的一个集合,这里我们将它们过滤掉。

【讨论】:

    【解决方案2】:

    我怀疑您是否可以使用元组 (and this topic confirms it) 来实现这一点。 但是你要找的是Power Set

    考虑这段代码:

    object PowerSetTest extends Application {
      val ls = List(1, 2, 3, 4)
      println(power(ls.toSet).filter(_.size > 1))
    
      def power[A](t: Set[A]): Set[Set[A]] = {
        @annotation.tailrec
        def pwr(t: Set[A], ps: Set[Set[A]]): Set[Set[A]] =
          if (t.isEmpty) ps
          else pwr(t.tail, ps ++ (ps map (_ + t.head)))
    
        pwr(t, Set(Set.empty[A]))
      }
    }
    

    运行它会给你:

    Set(Set(1, 3), Set(1, 2), Set(2, 3), Set(1, 2, 3, 4), Set(3, 4), Set(2, 4), Set(1, 2, 4), Set(1, 4), Set(1, 2, 3), Set(2, 3, 4), Set(1, 3, 4))
    

    您可以阅读here了解更多信息

    【讨论】:

    • 已经有一个subsets 方法用于Set,它在所有子集上返回一个IteratorList(1,2,3,4).toSet.subsets.filter(_.size > 1).toSet
    猜你喜欢
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2019-10-12
    • 2019-09-07
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多