简体   繁体   English

Python,有规律的空白列表

[英]Python, list with regular gaps

I want to create a python list with regular gaps.我想创建一个带有常规间隙的 python 列表。 I have a general idea of how I can do it, but is there a short way to do it or an inbuilt function to do this.我对如何做到这一点有一个大致的了解,但是有没有捷径可以做到这一点或有一个内置函数来做到这一点。

Suppose I want to create a list from 1 to 200, with gaps of 50. The list would be [1,..,50,101,..,150], ie the sequence from 51 to 100 and 151 to 200 is not in the list.假设我想创建一个从 1 到 200 的列表,间隔为 50。该列表将是 [1,..,50,101,..,150],即从 51 到 100 和 151 到 200 的序列不在列表。

def create_list_step(start,end,step):
     result = []
     current = start
     while current < end:
          smallinterval = current + step
          result = result + list(range(current, smallinterval))
          current = smallinterval + step
    return result

我不认为有一个内置函数,但这可以使用range的串联轻松完成:

final = list(range(1, 51)) + list(range(101, 151))

One way is to define a function which skips the gaps for you.一种方法是定义一个为您跳过空白的函数。

from itertools import chain

def gappy(start, rng, n):
    return chain(*(list(range(2*i*rng+1, (2*i+1)*rng+1)) for i in range(n)))

list(gappy(1, 50, 3))

# [1, 2, 3, ..., 48, 49, 50, 101, 102, 103, ...,
#  148, 149, 150, 201, 202, 203, ..., 248, 249, 250]

You could use list comprehensions:您可以使用列表推导式:

start = 5
stop = 17
gap = 3

a = [x for x in range(start, stop + 1) if ((x - start) // gap) % 2 == 0]

This is one-liner that should do it:这是应该这样做的单线:

[i for i in range(200) if (i-1)/50%2==0] #Python 2.x
[i for i in range(200) if (i-1)//50%2==0] #Python 3.x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM