Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generationg a list from user-input dynamically

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!!

like image 685
MacUsers Avatar asked Mar 12 '26 00:03

MacUsers


2 Answers

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.

like image 140
GP89 Avatar answered Mar 14 '26 15:03

GP89


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:

  • An explanation of the unpacking operator *
  • The official docs
like image 36
unutbu Avatar answered Mar 14 '26 14:03

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!