Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Scala equivalent for the python enumerate?

I'd like the convienience of

for i, line in enumerate(open(sys.argv[1])):   print i, line 

when doing the following in Scala

for (line <- Source.fromFile(args(0)).getLines()) {   println(line) } 
like image 488
Abhinav Sharma Avatar asked Jun 26 '11 20:06

Abhinav Sharma


People also ask

Is enumerate in Python?

Enumerate() in PythonEnumerate() method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method.

What type is enumerate Python?

By definition, an enumeration is a set of members that have associated unique constant values. Enumeration is often called enum. Python provides you with the enum module that contains the Enum type for defining new enumerations. And you define a new enumeration type by subclassing the Enum class.

Is enumerate faster than for loop Python?

Using enumerate() is more beautiful but not faster for looping over a collection and indices. Mind your Python version when looping over two collections - use itertools for Python 2.

What is enumerate method in Python?

enumerate() allows us to iterate through a sequence but it keeps track of both the index and the element. enumerate(iterable, start=0) The enumerate() function takes in an iterable as an argument, such as a list, string, tuple, or dictionary.


1 Answers

You can use the zipWithIndex from Iterable trait:

for ((line, i) <- Source.fromFile(args(0)).getLines().zipWithIndex) {    println(i, line) } 
like image 105
rafalotufo Avatar answered Sep 28 '22 00:09

rafalotufo