首页 > 解决方案 > 遍历具有范围的python列表中的项目列表

问题描述

我有一个类似这样的列表,里面有一个范围:

我想把它作为一个逗号分隔的值来扩展范围。

当我尝试使用 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 不包括最后一个元素。有更好的方法来处理这个吗?

标签: python

解决方案


在末尾添加 +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)

如果它解决了您的问题,请接受并打勾;)


推荐阅读