如何从列表中选择一系列数字?

时间:2017-01-24 16:52:09

标签: python list python-3.x filter sequence

我有一个起始编号和一个结尾编号 从这些数字我需要选择一系列数字 序列并不总是相同。

示例:

startnumber = 1
endnumber = 32

我需要创建一个具有特定序列的数字列表
体育
3个数字是,2个数字没有,3个数字是,2个数字没有..等等

预期产出:

[[1-3],[6-8],[11-13],[16-18],[21-23],[26-28],[31-32]]

(最后只剩下2个数字(31和32))

在python中有一种简单的方法可以从一系列数字中选择行序列吗?

3 个答案:

答案 0 :(得分:4)

numbers = range(1,33)
take = 3
skip = 2
seq = [list(numbers[idx:idx+take]) for idx in range(0, len(numbers),take+skip)]

答案 1 :(得分:1)

推断出来:

def get_data(data, filterfunc=None):
    if filterfunc is None:
        filterfunc = lambda: True  # take every line

    result = []
    sub_ = []
    for line in data:
        if filterfunc():
            sub_.append(line)
        else:
            if sub_:
                result.append(sub_)
                sub_ = []

    return result

# Example filterfunc
def example_filter(take=1, leave=1):
    """example_filter is a less-fancy version of itertools.cycle"""

    while True:
        for _ in range(take):
            yield True
        for _ in range(leave):
            yield False

# Your example
final = get_data(range(1, 33), example_filter(take=3, leave=2))

正如example_filter的docstring中所提到的,get_data的filterfunc实际上只是期望基于呼叫的TrueFalse。您可以轻松地将其更改为签名:

def filterfunc(some_data: object) -> bool:

这样你就可以根据值(甚至是索引)确定是取走还是离开,但它目前不需要参数,只是作为一个不太神奇的itertools.cycle的函数(因为它应该返回它的值呼叫,而不是迭代)

答案 2 :(得分:1)

from itertools import islice
def grouper(iterable, n, min_chunk=1):
    it = iter(iterable)
    while True:
       chunk = list(islice(it, n))
       if len(chunk) < min_chunk:
           return
       yield chunk

def pick_skip_seq(seq, pick, skip, skip_first=False):
    if skip_first:
        ret = [ x[skip:] for x in grouper(seq, pick+skip, skip+1) ]
    else:
        ret = [ x[:pick] for x in grouper(seq, pick+skip) ]
    return ret

pick_skip_seq(range(1,33), 3, 2)提供所需的清单。

pick_skip_seq(seq, pick, skip, skip_first=False)中, seq是要选择/跳过的序列, pick / skip不是。选择/跳过的元素, 如果skip_first设置为True 这种行为是可取的。

grouper返回n个元素的块,它 忽略最后一组,如果它少了 比min_chunk元素。 它源于给出的东西 https://stackoverflow.com/a/8991553/1921546

演示:

# pick 3 skip 2 
for i in range(30,35):
    print(pick_skip_seq(range(1,i), 3, 2))

# skip 3 pick 2 
for i in range(30,35):
    print(pick_skip_seq(range(1,i), 3, 2, True))

pick_skip_seq的替代实现:

from itertools import chain,cycle,repeat,compress
def pick_skip_seq(seq, pick, skip, skip_first=False):
    if skip_first:
        c = cycle(chain(repeat(0, skip), repeat(1, pick)))
    else:
        c = cycle(chain(repeat(1, pick), repeat(0, skip)))
    return list(grouper(compress(seq, c), pick))

所有使用的内容都记录在此处:https://docs.python.org/3/library/itertools.html#itertools.compress