Python:根据索引范围将列表拆分为子列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18570740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Split a list into sub-lists based on index ranges
提问by 2one
UPDATED:
更新:
In python, how do i split a list into sub-lists based on index ranges
在python中,如何根据索引范围将列表拆分为子列表
e.g. original list:
例如原始列表:
list1 = [x,y,z,a,b,c,d,e,f,g]
using index ranges 0 - 4:
使用索引范围 0 - 4:
list1a = [x,y,z,a,b]
using index ranges 5-9:
使用索引范围 5-9:
list1b = [c,d,e,f,g]
thanks!
谢谢!
I already known the (variable) indices of list elements which contain certain string and want to split the list based on these index values.
我已经知道包含特定字符串的列表元素的(变量)索引,并希望根据这些索引值拆分列表。
Also need to split into variable number of sub-lists! i.e:
还需要拆分成可变数量的子列表!IE:
list1a
list1b
.
.
list1[x]
采纳答案by Mark R. Wilkins
Note that you can use a variable in a slice:
请注意,您可以在切片中使用变量:
l = ['a',' b',' c',' d',' e']
c_index = l.index("c")
l2 = l[:c_index]
This would put the first two entries of l in l2
这会将 l 的前两个条目放入 l2
回答by no1
list1a=list[:5]
list1b=list[5:]
回答by TerryA
In python, it's called slicing. Here is an example of python's slice notation:
在python中,它被称为切片。这是python切片符号的一个例子:
>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l']
>>> print list1[:5]
['a', 'b', 'c', 'd', 'e']
>>> print list1[-7:]
['f', 'g', 'h', 'i', 'j', 'k', 'l']
Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.
请注意如何积极或消极地切片。当您使用负数时,这意味着我们从右向左切片。
回答by no1
list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]
回答by Jon Clements
If you already know the indices:
如果您已经知道索引:
list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]
Note that we're adding +1 to the end to make the range inclusive...
请注意,我们在末尾添加 +1 以使范围包含...