Python 如何引用列表中不同范围的值?
我想做的是引用列表中的几个不同范围,即我想要4-6个元素,12-18个元素,等等。这是我最初的尝试:Python 如何引用列表中不同范围的值?,python,list,slice,Python,List,Slice,我想做的是引用列表中的几个不同范围,即我想要4-6个元素,12-18个元素,等等。这是我最初的尝试: test = theList[4:7, 12:18] 我希望它能做同样的事情: test = theList[4,5,6,12,13,14,15,16,17] 但是我有一个语法错误。最好/最简单的方法是什么 您可以添加这两个列表 >>> theList = list(range(20)) >>> theList[4:7] + theList[12:18]
test = theList[4:7, 12:18]
我希望它能做同样的事情:
test = theList[4,5,6,12,13,14,15,16,17]
但是我有一个语法错误。最好/最简单的方法是什么 您可以添加这两个列表
>>> theList = list(range(20))
>>> theList[4:7] + theList[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]
注意:如果要循环结果,不需要将结果转换为
列表
您可以添加@Bhargav_Rao所述的两个列表。更一般地说,您还可以使用列表生成器语法:
test = [theList[i] for i in range(len(theList)) if 4 <= i <= 7 or 12 <= i <= 18]
test=[theList[i]for i in range(len(theList)),如果4test=the_list[4:7]+the_list[12:18]
你说的“reference”是什么意思?你想对原始列表进行某种查看,以便更改会影响它吗?谢谢!!这看起来非常明显…(但在我的辩护中,我刚刚学习了python…)很高兴能帮助你。祝你一切顺利。(尽快:P)我该如何创建一个列表?很抱歉。我习惯于R,在R中,如果我只想要一个从1到7的序列,我可以做一些类似于seq=1:7的事情,这将生成一个1,2,3,4,5,6,7的数组。我在python中如何做到这一点?@lukehawk看看range
函数。你可以阅读更多关于它的信息
test = [theList[i] for i in range(len(theList)) if 4 <= i <= 7 or 12 <= i <= 18]