3

As the title says, I'm processing some command-line options to create a list from user input, like this: "3,28,2". This is what I got so far:

>>> rR = "3,28,2"
>>> rR = re.split(r"[\W]+", rR)
>>> map(int, xrange( int(rR[0]),int(rR[1]),int(rR[2]) ))
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27]
>>>

FYI, the re.split() is because users are allowed to use comma (,) or space or both at the same time as the delimiter.

My question is how can I "automate" the xrange(object) bit so that user-input can be with or without start and step value (i.e. "3,28,2" vs. "3,28" vs. "28"). len(rR) does tell me the number of elements in the input but I'm kind of lost here with how can I use that information to write the xrange/range part dynamically.

Any idea(s)? Also trying to make my code as efficient as possible. So, any advise on that would be greatly appreciated. Cheers!!

MacUsers
  • 2,091
  • 3
  • 35
  • 56
  • 1
    I don't get why you apply `int` to `xrange`. Independently to your problem, why don't you just write `range(int(rR[0]),int(rR[1]),int(rR[2]))`? – Guillaume Lemaître May 15 '13 at 12:19
  • 1
    @GuillaumeLemaître I don't understand that too, `xrange` is not useful when you need to convert it all to a list – jamylak May 15 '13 at 12:25
  • I'm guessing he uses the `xrange` for something else, but used the `map(int` to display the result here, although `list()` would have been clearer – GP89 May 15 '13 at 12:33
  • @GuillaumeLemaître: There are millions of numbers in the list and I didn't want to load the entire list into the memory, hence using xrange. It was just a cut-n-paste from the original script to show you guys what I'm after. But point noted. Thanks! – MacUsers May 15 '13 at 12:57

3 Answers3

6

Try this:

>>> rR = "3,28,2"
>>> rR = re.split(r"[\W]+", rR)
>>> map(int, xrange(*map(int, rR)))
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27]
>>>

the * will unpack the elements into arguments for xrange.

GP89
  • 6,600
  • 4
  • 36
  • 64
  • @GP89: Didn't know that `*` trick; never ever thought it's gonna be that easy. thanks a lot. Only one prob is: you got one tailing `)` missing in the `map()`. Cheers!! – MacUsers May 15 '13 at 12:40
  • @MacUsers So i did! I've edited it now just for completeness :) – GP89 May 15 '13 at 16:30
2
In [46]: import re

In [47]: rR = "3,28,2"

In [48]: range(*map(int, re.split(r"\W+", rR)))
Out[48]: [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27]

References:

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

I prefer (list|generator) comprehensions to map. I think they are considered more "pythonic", generally.

>>> rR = "3,28,2"
>>> range(*(int(x) for x in re.split(r"[\W]+", rR)))
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27]
Matt Anderson
  • 19,311
  • 11
  • 41
  • 57