如何引用列表中各种范围的值?

时间:2015-07-06 18:44:31

标签: python list slice

我想要做的是从列表中引用几个不同的范围,即我想要4-6个元素,12-18个元素等。这是我最初的尝试:

test = theList[4:7, 12:18]

我希望提供的内容与:

相同
test = theList[4,5,6,12,13,14,15,16,17]

但是我遇到了语法错误。最好/最简单的方法是什么?

3 个答案:

答案 0 :(得分:8)

您可以添加两个列表。

>>> theList = list(range(20))
>>> theList[4:7] + theList[12:18]
[4, 5, 6, 12, 13, 14, 15, 16, 17]

答案 1 :(得分:2)

您也可以使用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

答案 2 :(得分:1)

您可以将两个列表添加为@Bhargav_Rao。更一般地说,您还可以使用列表生成器语法:

test = [theList[i] for i in range(len(theList)) if 4 <= i <= 7 or 12 <= i <= 18]