2 回答
TA贡献1815条经验 获得超10个赞
在末尾添加 +1 作为范围排除最后一个数字
a = ['1','2','3-10','15-20']
b = []
for item in a:
if '-' in item:
print('The value of item is :' , item)
start = item.split('-')[0]
print('The value of start is :' , start)
end = item.split('-')[1]
print('The value of end is :' , end)
for i in range(int(start),int(end)+1):
b.append(i)
else:
b.append(item)
print('The value of b is : ', b)
如果它解决了您的问题,请接受并打勾;)
TA贡献1887条经验 获得超5个赞
您可以使用嵌套列表推导式:
a = ['1','2','3-10','15-20']
expanded = [list(range(int(i.split('-')[0]), int(i.split('-')[1])+1)) if '-' in i else [int(i)] for i in a]
flatten = ','.join(map(str, [i for sublist in expanded for i in sublist]))
返回:
1,2,3,4,5,6,7,8,9,10,15,16,17,18,19,20
添加回答
举报