请问在python中如何让'[1,2,3,6~10]'返回[1,2,3,6,7,8,9,10]列表?
请问在python中如何让'[1,2,3,6~10]'返回[1,2,3,6,7,8,9,10]列表?
谢谢
回答:
def f(s): parts = s[1:-1].split(',')
l = []
for part in parts:
ranges = part.split('~')
if len(ranges) == 1:
l.append(int(ranges[0]))
else:
for i in range(int(ranges[0]), int(ranges[1])+1):
l.append(i)
return l
if __name__ == '__main__':
print(f('[1,2,3,6~10]'))
回答:
from functools import reduce
sampleListStr = '[1,2,3,6~10]'
sampleList = sampleListStr.strip('[]').split(',')
result = list(reduce(lambda x, y: x + y, [[int(element)] if '~' not in element else list(reduce(lambda x, y: range(x, y+1), [int(element1) for element1 in element.split('~')])) for element in sampleList]))
以上是 请问在python中如何让'[1,2,3,6~10]'返回[1,2,3,6,7,8,9,10]列表? 的全部内容, 来源链接: utcz.com/a/165104.html