Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

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:

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]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top