本文主要介绍Python中,指定数字的范围,生成包含正数和负数的列表(list)的方法,及实现的示例代码。

1、使用列表生成器

nums = [y for x in range(6,10) for y in (x,-x)]
print(nums)
[6, -6, 7, -7, 8, -8, 9, -9]

2、使用函数方法生成

def range_with_negatives(start, end):
    for x in range(start, end):
        yield x
        yield -x

用法:

list(range_with_negatives(6, 10))

3、使用*实现

>>> [*range(6, 10), *range(-9, -5)]
[6, 7, 8, 9, -9, -8, -7, -6]

4、使用itertools.chain()实现

import itertools
list(itertools.chain(range(6, 10), range(-9, -5)))

或者

>>> list(itertools.chain(*((x, -x) for x in range(6, 10))))
[6, -6, 7, -7, 8, -8, 9, -9]

5、使用product和starmap

from itertools import product, starmap
from operator import mul

list(starmap(mul, product((-1, 1), range(6, 10))))

推荐文档