Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nim enumerate function like Python

Learning Nim and I like it resemblence of Python (but fast). In Python I can do this:

item_index = [(idx, itm) for idx, itm in enumerate(row)]

Im looking for a way to enumerate a Nim sequence so I would write this:

item_index = lc[(idx, itm) | (idx, itm <- enumerate(row))]

Does this functionality exist? I'm sure you could create it, maybe with a proc, template or macro it but I'm still very new, and these seem hard to create myself still. Here is my attempt:

iterator enumerate[T](s: seq[T]): (int, T) =
    var i = 0
    while i < len(s):
        yield (i, s[i])
        i += 1
like image 533
Peheje Avatar asked Jan 05 '18 20:01

Peheje


People also ask

What is the use of enumerate in Python?

The enumerate () function takes a collection (e.g. a tuple) and returns it as an enumerate object. The enumerate () function adds a counter as the key of the enumerate object. A Number. Defining the start number of the enumerate object.

How do you enumerate a list in Python?

Python eases the programmers’ task by providing a built-in function enumerate () for this task. Enumerate () 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.

How to enumerate a counter in Python?

Python eases the programmers’ task by providing a built-in function enumerate() for this task. Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object.

How do I use enumerate () in a loop?

You can use enumerate () in a loop in almost the same way that you use the original iterable object. Instead of putting the iterable directly after in in the for loop, you put it inside the parentheses of enumerate (). You also have to change the loop variable a little bit, as shown in this example:


1 Answers

I'm a newbie with nim, and I'm not really sure what you want, but... If you use two variables in a for statement, you will get the index and the value:

for x, y in [11,22,33]:
  echo x, " ", y

Gives:

0 11
1 22
2 33

HTH.

like image 128
aMike Avatar answered Nov 02 '22 23:11

aMike