迭代非顺序范围

时间:2017-05-25 23:56:19

标签: python python-3.x

我想迭代非连续范围。换句话说,根据用户输入跳过某些索引/元素,如此。

>>> 0
>>> 3
>>> 4
>>> 6
>>> 7
>>> 8
>>> 9

我无法弄清楚我是如何尝试这种方法的。

import re

>>> crazyrange = '0, 3-4, 6, 7-9'    # User input string
>>> crazyrange = re.split (', ', crazyrange)
>>> crazyrange
['0', '3-4', '6', '7-9']
>>>
>>> masterlist = []
>>> def get_range (values):
    rangelist = []
    for i in range (int (values [0]), int (values [1]) + 1):
        rangelist.append (i)
    return rangelist
>>>
>>> for i in crazyrange:
    if '-' in i:
        values = i.split ('-')
        masterlist.extend (get_range (values))
    else:
        masterlist.append (int (i))
>>>
>>> masterlist
[0, 3, 4, 6, 7, 8, 9]

有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

你的代码看起来很不错,但是你不需要re,你可以通过使用python的range函数和yield来自生成器函数的项来整理它:

crazyrange = '0, 3-4, 6, 7-9'    # User input string

def get_range(range_string):
    items = range_string.replace(" ", "").split(",")
    for i in items:
        if '-' in i:
            start, end = i.split('-')
            for j in range(int(start), int(end)+1): # range() is not inclusive
                yield j
        else:
            yield int(i)

for x in get_range(crazyrange):
    print x

print list(get_range(crazyrange))
# [0, 3, 4, 6, 7, 8, 9]

还有一个没有显式循环的选项:

crazyrange = '0, 3-4, 6, 7-9'    # User input string
import itertools
items = [i.split("-") for i in crazyrange.split(", ")]
range_list = [range(int(i[0]), int(i[-1])+1) for i in items]
print list(itertools.chain(*range_list))

或者这个选项可能是最简单的:

crazyrange = '0, 3-4, 6, 7-9'    # User input string

def get_range(item):
    pair = item.split('-')  # may only be one item, but that's OK
    return range(int(pair[0]), int(pair[-1])+1)

items = crazyrange.split(', ')
print [i for item in items for i in get_range(item)]
# [0, 3, 4, 6, 7, 8, 9]

答案 1 :(得分:1)

使用list comprehension

可以在更少的代码中使用相同的输出
crazyrange = '0, 3-4, 6, 7-9'

ranges = [range(int(k.split("-")[0]), int(k.split("-")[-1]) +1) for k in crazyrange.split(',')]

print(ranges)
print([j for k in ranges for j in k])

输出:

[range(0, 1), range(3, 5), range(6, 7), range(7, 10)]
[0, 3, 4, 6, 7, 8, 9]