【问题标题】:Index of a list of lists in scalascala中列表的索引
【发布时间】:2013-12-07 17:14:07
【问题描述】:

谁能解释一下下面的代码是做什么的? (炒作返回List[(Int,Int,Set[Int])])

  def all(): List[(Int, Int, Set[Int])] = 
  {
       list.zipWithIndex flatMap 
       {
         case (row, r) =>
         row.zipWithIndex.withFilter(_._1 == 0) map 
         {
            case (col, c) => (r, c,  hyp(r, c))
         }
       }
   } 

list 被定义为整数列表的列表。我知道 '==0' 是因为该方法需要访问 0 的元素,但我不明白 zipWithIndex 究竟做了什么。谢谢

【问题讨论】:

    标签: list scala collections indexing


    【解决方案1】:

    不是逐行解释,但我认为理解的关键可能如下:

    ('a' to 'c').zipWithIndex
    // Vector((a,0), (b,1), (c,2))
    

    【讨论】:

      【解决方案2】:

      zipWithIndex 给出(元素,索引)对的列表。

      val list = List(1,2,3,101,330,302)    
      
      list.zipWithIndex //> List((1,0), (2,1), (3,2), (101,3), (330,4), (302,5))
      

      所以在给定的例子中:

      def all(): List[(Int, Int, Set[Int])] = 
      {
         // if list              = List( list1,      list2,      ...)
         //    list.zipWithIndex = List( (list1, 0), (list2, 1), ...)
         list.zipWithIndex flatMap 
         {
           case (row, r) =>  // it gets (list1, 0) etc.
           // if row          = ( elem0,      elem1,      ...) // list1
           //    rowWithIndex = ( (elem0, 0), (elem1, 1), ...)
           row.zipWithIndex.withFilter(_._1 == 0) map  // check for elem0 == 0 etc.
           {
              // so col here is cell value, r is row index, c is column index
              case (col, c) => (r, c,  hyp(r, c))   
      
           }
         }
      } 
      

      【讨论】:

        【解决方案3】:

        我一直在观察问题的出现,这些问题显然与编写数独求解器的一些任务有关,而且我也一直在做一种“软件开发危险”来弄清楚设计的问题是什么发布...

        无论如何,我的猜测是这个函数返回所有未解决的数独单元格的坐标和可能性。

        【讨论】:

          猜你喜欢
          • 2016-10-07
          • 1970-01-01
          • 2013-09-19
          • 2013-07-26
          • 1970-01-01
          • 1970-01-01
          • 2018-07-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多