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

4

3 回答 3

6

尝试这个:

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

* 会将元素解包到 xrange 的参数中。

于 2013-05-15T12:09:37.087 回答
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]

参考:

于 2013-05-15T12:33:40.380 回答
1

我更喜欢 (list|generator) 理解而不是map. 我认为它们通常被认为更“pythonic”。

>>> 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]
于 2013-05-15T12:12:21.013 回答