用Python生成一个数字序列

2024-05-01 21:23:29 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答
>>> ','.join('{},{}'.format(i, i + 1) for i in range(1, 100, 4))
'1,2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65,66,69,70,73,74,77,78,81,82,85,86,89,90,93,94,97,98'

这是一个快速而肮脏的解决方案。

现在,对于适合于不同类型进展问题的解决方案:

def deltas():
    while True:
        yield 1
        yield 3
def numbers(start, deltas, max):
    i = start
    while i <= max:
        yield i
        i += next(deltas)
print(','.join(str(i) for i in numbers(1, deltas(), 100)))

下面是使用itertools实现的类似想法:

from itertools import cycle, takewhile, accumulate, chain

def numbers(start, deltas, max):
    deltas = cycle(deltas)
    numbers = accumulate(chain([start], deltas))
    return takewhile(lambda x: x <= max, numbers)

print(','.join(str(x) for x in numbers(1, [1, 3], 100)))

包括对您期望的确切序列的一些猜测:

>>> l = list(range(1, 100, 4)) + list(range(2, 100, 4))
>>> l.sort()
>>> ','.join(map(str, l))
'1,2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65,66,69,70,73,74,77,78,81,82,85,86,89,90,93,94,97,98'

作为一行:

>>> ','.join(map(str, sorted(list(range(1, 100, 4))) + list(range(2, 100, 4))))

(顺便说一下,这是与Python 3兼容的)

从1,2,5,6,9,10。。。可以用余数1或2除以4。

>>> ','.join(str(i) for i in xrange(100) if i % 4 in (1,2))
'1,2,5,6,9,10,13,14,...'

相关问题 更多 >