Concatenating two range function results

2019-01-22 05:39发布

Does range function allows concatenation ? Like i want to make a range(30) & concatenate it with range(2000, 5002). So my concatenated range will be 0, 1, 2, ... 29, 2000, 2001, ... 5001

Code like this does not work on my latest python (ver: 3.3.0)

range(30) + range(2000, 5002)

7条回答
Evening l夕情丶
2楼-- · 2019-01-22 06:27

I came to this question because I was trying to concatenate an unknown number of ranges, that might overlap, and didn't want repeated values in the final iterator. My solution was to use set and the union operator like so:

range1 = range(1,4)
range2 = range(2,6)
concatenated = set.union(set(range1), set(range2)
for i in concatenated:
    print(i)
查看更多
登录 后发表回答