當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Scala List splitAt()用法及代碼示例


splitAt()方法屬於類List的值成員。它用於在給定位置將給定列表拆分為前綴/後綴對。

函數定義: def splitAt(n: Int): (List[A], List[A])

Where, n is the position at which we need to split.



返回類型: It returns a pair of lists consisting of the first n elements of this list, and the other elements.

範例1:

// Scala program of splitAt() 
// method 
  
// Creating object 
object GfG 
{  
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating a List  
        val list = List("a", "b", "c", "d", "e", "f") 
          
        // Applying splitAt method  
        val result = list.splitAt(3) 
          
        // Displays output 
        println(result) 
      
    } 
}
輸出:
(List(a, b, c), List(d, e, f))

範例2:

// Scala program of splitAt() 
// method 
  
// Creating object 
object GfG 
{  
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating a List  
        val list = List(1, 2, 3, 4, 5, 6, 7) 
          
        // Applying splitAt method  
        val result = list.splitAt(4) 
          
        // Displays output 
        println(result) 
      
    } 
}
輸出:
(List(1, 2, 3, 4), List(5, 6, 7))


相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Scala List splitAt() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。