我有一个类似这样的列表,里面有一个范围:
我想把它作为逗号分隔值,范围扩大。
当我尝试使用 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)
范围不包括最后一个元素。有更好的方法来处理这个问题吗?
请您参考如下方法:
在最后加上 +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)
如果解决了您的问题,请采纳并打勾;)
