Slicing a list using a variable, in Python

眉间皱痕 提交于 2019-12-17 16:15:00

问题


Given a list

a = range(10)

You can slice it using statements such as

a[1]
a[2:4]

However, I want to do this based on a variable set elsewhere in the code. I can easily do this for the first one

i = 1
a[i]

But how do I do this for the other one? I've tried indexing with a list:

i = [2, 3, 4]
a[i]

But that doesn't work. I've also tried using a string:

i = "2:4"
a[i]

But that doesn't work either.

Is this possible?


回答1:


that's what slice() is for:

a = range(10)
s = slice(2,4)
print a[s]

That's the same as using a[2:4].




回答2:


Why does it have to be a single variable? Just use two variables:

i, j = 2, 4
a[i:j]

If it really needs to be a single variable you could use a tuple.




回答3:


>>> a=range(10)
>>> i=[2,3,4]

>>> a[i[0]:i[-1]]
range(2, 4)

>>> list(a[i[0]:i[-1]])
[2, 3]



回答4:


With the assignments below you are still using the same type of slicing operations you show, but now with variables for the values.

a = range(10)
i = 2
j = 4

then

print a[i:j]
[2, 3]


来源:https://stackoverflow.com/questions/10573485/slicing-a-list-using-a-variable-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!