Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of every n-th item in a given list

This is a simple exercise I am solving in Scala: given a list l return a new list, which contains every n-th element of l. If n > l.size return an empty list.

def skip(l: List[Int], n: Int) = 
  Range(1, l.size/n + 1).map(i => l.take(i * n).last).toList

My solution (see above) seem to work but I am looking for smth. simpler. How would you simplify it?

like image 674
Michael Avatar asked Aug 10 '14 09:08

Michael


People also ask

How do you find the nth element of a list in Python?

Use list indexing to get the nth element of a list. Use list indexing syntax list[index] with n - 1 as index , where n represents a value's placement in the list, to retrieve the respective nth element of a list.

How do you select every other item in a list Python?

Use enumerate() to access every other element in a list {use-for-loop-enumerate} Use the syntax for index, element in enumerate(iterable) to iterate through the list iterable and access each index with its corresponding element . At each iteration, use the syntax if index % 2 == 0 to check if index is even.

How do you get every second element in a list?

To return every second element we have to change the start value to 1. Now, create a function that uses a for loop and the range function to generate list indexes. The first argument (start) is equal to 1 and the second argument (end) is equal to the length of the list.


2 Answers

scala> def skip[A](l:List[A], n:Int) = 
         l.zipWithIndex.collect {case (e,i) if ((i+1) % n) == 0 => e} // (i+1) because zipWithIndex is 0-based
skip: [A](l: List[A], n: Int)List[A]

scala> val l = (1 to 10).toList
l: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> skip(l,3)
res2: List[Int] = List(3, 6, 9)

scala> skip(l,11)
res3: List[Int] = List()
like image 112
Marth Avatar answered Sep 18 '22 05:09

Marth


Somewhat simpler:

scala> val l = (1 to 10).toList
l: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

// n == 3

scala> l.drop(2).grouped(3).map(_.head).toList
res0: List[Int] = List(3, 6, 9)

// n > l.length

scala> l.drop(11).grouped(12).map(_.head).toList
res1: List[Int] = List()

(the toList just to force the iteratot to be evaluated)

Works with infinite lists:

Stream.from(1).drop(2).grouped(3).map(_.head).take(4).toList
res2: List[Int] = List(3, 6, 9, 12)
like image 36
The Archetypal Paul Avatar answered Sep 21 '22 05:09

The Archetypal Paul