在Scala中访问列表中的索引 [英] Accessing an index in a list in Scala

查看:535
本文介绍了在Scala中访问列表中的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个方法"all()",该方法返回一个元组列表;当函数在列表中满足0时,每个元组将包含与特定给定行和列相关的行,列和集合.我已经编写了"hyp"函数,该函数返回所需的设置部分,例如:Set(1,2). 我正在使用列表列表:

I have to write a method "all()" which returns a list of tuples; each tuple will contain the row, column and set relevant to a particular given row and column, when the function meets a 0 in the list. I already have written the "hyp" function which returns the set part I need, eg: Set(1,2). I am using a list of lists:

| 0 | 0 | 9 |
| 0 | x | 0 |
| 7 | 0 | 8 |

如果Set(1,2)引用标记为x的单元格,则all()应该返回:(1,1,Set(1,2)) 其中1,1是行和列的索引.

If Set (1,2) are referring to the cell marked as x, all() should return: (1,1, Set(1,2)) where 1,1 are the index of the row and column.

我使用zipWithIndex编写了此方法,但无法使用此功能.在这种情况下,有没有更简单的方法来访问索引?预先感谢

I wrote this method by using zipWithIndex but I can't use this function. Is there any simpler way how to access an index as in this case? Thanks in advance

代码:

 def all(): List[(Int, Int, Set[Int])] = 
 {
    puzzle.list.zipWithIndex flatMap 
    { 
      rowAndIndex =>
      rowAndIndex._1.zipWithIndex.withFilter(_._1 == 0) map 
      { 
        colAndIndex =>
        (rowAndIndex._2, colAndIndex._2,  hyp(rowAndIndex._2, colAndIndex._2)) 
      }
    }
 } 

(_._ 1 == 0)是因为该函数仅在网格中找到0时才必须返回(Int,Int,Set())

The (_._1 == 0 ) is because the function has to return the (Int,Int, Set()) only when it finds a 0 in the grid

推荐答案

all函数可以简化为:

// Given a list of list
puzzle.list = List(List(0, 0, 9), List(0, 5, 0), List(7, 0, 8))

for {

  (row, rIndex) <- puzzle.list.zipWithIndex   // List of (row, index)
                                              // List( (List(0,0,9), 0) ...

  (col, cIndex) <- row.zipWithIndex;          // List of (col, index)
                                              // List( (0,0), (0,1), (9, 2) ...

  if (col == 0)                               // keep only col with 0

} yield (rIndex, cIndex, hyp(rIndex, cIndex))   

这篇关于在Scala中访问列表中的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆