我有一个像这样的列表,里面有一个范围:
我想将其作为扩展范围的逗号分隔值获取。
当我尝试使用forloop遍历列表中的项目时,我没有得到想要的结果。
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)):
b.append(i)
else:
b.append(item)
print('The value of b is : ', b)
range不包含最后一个元素。还有更好的方法来解决这个问题吗?
答案 0 :(得分:1)
末尾添加+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)
如果可以解决您的问题,请接受并勾选;)
答案 1 :(得分:0)
您可以使用嵌套列表推导:
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