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
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.
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.
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))
You can try this:
val ziplist = list zip (Stream from 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With