Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
遍历python列表中的项目列表,该列表的范围为_Python - Fatal编程技术网

遍历python列表中的项目列表,该列表的范围为

遍历python列表中的项目列表,该列表的范围为,python,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

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

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

当我尝试使用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)

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

您可以使用嵌套列表理解:

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

范围不包括最后一项。如果将“+1”添加到末尾,它将占用整个范围。为什么要列出(range())?默认ryt值的范围结果列表?我对列表的理解做了一些修改:-print reduce(lambda x,y:x+y,[range(int(r.split('-'))[0]),int(r.split('-')[1])+1)如果r else中的'-'表示a中的r,[int(r)],
range()
返回一个范围对象,而不是
list
oops!我没有检查python 3,我使用的是python 2 Good Day ji;)