Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zipWithIndex from 1 instead of 0

Tags:

scala

If I have a list and zipWithIndex

val list = List('a', 'b', 'c')
val ziplist = List.zipWithIndex
// List[(int, int)] = List(('a', 0), ('b', 1), ('c', 2))

If I want to index from 1 instead of 0, is there a smarter way than my current:

val ziplist = List.zipWithIndex.map( ele => (ele._1, ele._2 + 1))

Hope you guys can help!

Described in the summarization

like image 426
PaFko Avatar asked Sep 10 '19 09:09

PaFko


People also ask

How does zipWithIndex work?

Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition receives the largest index.

What is zipWithIndex in spark?

The zipWithIndex() transformation appends (or ZIPs) the RDD with the element indices. This is very handy when wanting to remove the header row (first row) of a file.


2 Answers

You could use LazyList.from(1) to generate indexes:

List('a', 'b', 'c').zip(LazyList.from(1)) // List((a,1), (b,2), (c,3))

If you're using Scala older than 2.13, you'd need to use Stream instead of LazyList:

List('a', 'b', 'c').zip(Stream.from(1)) // List((a,1), (b,2), (c,3))
like image 149
Krzysztof Atłasik Avatar answered Oct 06 '22 22:10

Krzysztof Atłasik


You can try this:

val ziplist = list zip (Stream from 1)
like image 3
Teena Vashist Avatar answered Oct 07 '22 00:10

Teena Vashist