我希望能够将诸如“1,2,5-7,10”之类的字符串转换为诸如[1,2,5,6,7,10]之类的python列表。我环顾四周找到this,但我想知道在Python中是否有一种简洁明了的方法。
答案 0 :(得分:28)
>>> def f(x):
... result = []
... for part in x.split(','):
... if '-' in part:
... a, b = part.split('-')
... a, b = int(a), int(b)
... result.extend(range(a, b + 1))
... else:
... a = int(part)
... result.append(a)
... return result
...
>>> f('1,2,5-7,10')
[1, 2, 5, 6, 7, 10]
答案 1 :(得分:4)
我能够对这个问题做出真正的理解:
>>> def f(s):
return sum(((list(range(*[int(j) + k for k,j in enumerate(i.split('-'))]))
if '-' in i else [int(i)]) for i in s.split(',')), [])
>>> f('1,2,5-7,10')
[1, 2, 5, 6, 7, 10]
>>> f('1,3-7,10,11-15')
[1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15]
假装理解的另一个答案只是for循环,因为最终的列表被丢弃了。 :)
对于python 2,您甚至可以删除对list
!
答案 2 :(得分:2)
这可能是一种矫枉过正,但我只是喜欢pyparsing:
from pyparsing import *
def return_range(strg, loc, toks):
if len(toks)==1:
return int(toks[0])
else:
return range(int(toks[0]), int(toks[1])+1)
def parsestring(s):
expr = Forward()
term = (Word(nums) + Optional(Literal('-').suppress() + Word(nums))).setParseAction(return_range)
expr << term + Optional(Literal(',').suppress() + expr)
return expr.parseString(s, parseAll=True)
if __name__=='__main__':
print parsestring('1,2,5-7,10')
答案 3 :(得分:1)
def rangeString(commaString):
def hyphenRange(hyphenString):
x = [int(x) for x in hyphenString.split('-')]
return range(x[0], x[-1]+1)
return chain(*[hyphenRange(r) for r in commaString.split(',')])
演示:
>>> list( f('1,2,5-7,10') )
[1, 2, 5, 6, 7, 10]
可轻松修改以处理负数或返回列表。还需要from itertools import chain
,但如果您不使用sum(...,[])
个对象(或range
)并且您不关心懒惰,则可以将sum(map(list,iters),[])
替换为{{1}}。
答案 4 :(得分:1)
没有理解胜过我的!
import re
def convert(x):
return sum((i if len(i) == 1 else list(range(i[0], i[1]+1))
for i in ([int(j) for j in i if j] for i in
re.findall('(\d+),?(?:-(\d+))?', x))), [])
最好的部分是我在理解的过程中两次使用变量i
。
>>> convert('1,2,5-7,10')
[1, 2, 5, 6, 7, 10]
答案 5 :(得分:1)
很短,很优雅(imho):
>>> txt = "1,2,5-7,10"
>>> # construct list of xranges
>>> xranges = [(lambda l: xrange(l[0], l[-1]+1))(map(int, r.split('-'))) for r in txt.split(',')]
>>> # flatten list of xranges
>>> [y for x in xranges for y in x]
[1, 2, 5, 6, 7, 10]
答案 6 :(得分:0)
从这里:https://gist.github.com/raczben/76cd1229504d82115e6427e00cf4742c
def number(a, just_try=False):
"""
Parse any representation of number from string.
"""
try:
# First, we try to convert to integer.
# (Note, that all integer can be interpreted as float and hex number.)
return int(a)
except:
# The order of the following convertions doesn't matter.
# The integer convertion has failed because `a` contains hex digits [x,a-f] or a decimal
# point ['.'], but not both.
try:
return int(a, 16)
except:
try:
return float(a)
except:
if just_try:
return a
else:
raise
def str2numlist(s):
"""
Convert a string parameter to iterable object.
"""
return [y for x in s.split(',') for y in str_ranges_to_list(x) ]
def str_ranges_to_list(s):
"""
Convert a string parameter to iterable object.
"""
s = s.strip()
try:
begin,end=s.split(':')
return range(number(begin), number(end))
except ValueError: # not enough values to unpack
return [number(s)]