Python Equivalent Of Haskell's [1..] (to Index A List)
I have a list of elements in python. I don't know the number of elements in the list. I would like to add indexes to the list. In Haskell, I could do the following zip [1..] 'abcde
Solution 1:
Just do list(enumerate(s))
. This iterates over the enumerate
object and converts it to a list
.
Solution 2:
You can simplify it with a list comprehension:
>>> [i for i in enumerate(s)]
Solution 3:
Using enumerate
is definitely the way to go, but here is a little bit more functional solution with toolz:
from toolz.itertoolz import iterate, zip
zip(iterate(lambda x: x + 1, 0), "abcdefghijklmnop")
Solution 4:
You can use the range
function with zip
.
For Python 2:
>>> s = "abcdefghijklmnop"
>>> zip(range(16),s)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n'), (14, 'o'), (15, 'p')]
For Python 3:
>>> s = "abcdefghijklmnop"
>>> list(zip(range(16),s))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n'), (14, 'o'), (15, 'p')]
Post a Comment for "Python Equivalent Of Haskell's [1..] (to Index A List)"