请问在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]列表?
谢谢

阅读 2.3k
2 个回答
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]))

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏