我想要做的是从一个列表中引用几个不同的范围,即我想要4-6元素,12 -18元素等等。这是我最初的尝试:
test = theList[4:7, 12:18]我希望它能做同样的事情:
test = theList[4,5,6,12,13,14,15,16,17]但我有语法错误。做这件事最好/最简单的方法是什么?
发布于 2015-07-06 18:45:38
您可以添加这两个列表。
>>> theList = list(range(20))
>>> theList[4:7] + theList[12:18]
[4, 5, 6, 12, 13, 14, 15, 16, 17]发布于 2015-07-06 18:49:27
您还可以使用itertools模块:
>>> from itertools import islice,chain
>>> theList=range(20)
>>> list(chain.from_iterable(islice(theList,*t) for t in [(4,7),(12,18)]))
[4, 5, 6, 12, 13, 14, 15, 16, 17] 注意,由于islice在每次迭代中返回一个生成器,它在内存使用方面比列表切片更好。
此外,您还可以使用一个函数进行更多的索引和一般方法。
>>> def slicer(iterable,*args):
... return chain.from_iterable(islice(iterable,*i) for i in args)
...
>>> list(slicer(range(40),(2,8),(10,16),(30,38)))
[2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 30, 31, 32, 33, 34, 35, 36, 37]注意:如果要循环结果,则不需要将结果转换为list!
发布于 2015-07-06 18:52:48
如@Bhargav_Rao所述,您可以添加这两个列表。更一般地,您还可以使用列表生成器语法:
test = [theList[i] for i in range(len(theList)) if 4 <= i <= 7 or 12 <= i <= 18]https://stackoverflow.com/questions/31253312
复制相似问题