如何引用列表中不同范围的值?

2024-10-01 15:37:14 发布

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

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

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

我希望它能做同样的事情:

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

但我有个语法错误。最好/最简单的方法是什么?你知道吗


Tags: 方法test元素列表事情语法错误thelist
3条回答

您可以添加这两个列表。你知道吗

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

也可以使用^{}模块:

>>> 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!你知道吗

你可以按照@Bhargav\u Rao所说的添加这两个列表。更一般地,还可以使用列表生成器语法:

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

相关问题 更多 >

    热门问题