在python中:变量作为切片数组的索引并不起作用

时间:2016-11-30 18:43:02

标签: python arrays

所以我试图使用变量获取一个数组,但不能正常工作。如果我将数字硬编码到indeces中,那么一切正常。为什么???

我的代码:

def play(startplay,stopplay):


    Y = x[startplay:startplay+5]
    # produces an empty list...

    Y = x[1:5]
    # produces the correct list 

2 个答案:

答案 0 :(得分:1)

startplay的价值是多少?如果它比list更长(或者是负数,但接近于startplay+5 >= 0的0),那么在切片时,您希望得到一个空的list

>>> test = [1, 2, 3]
>>> test[-5:0]  # Can't slice from negative to non-negative with implicit step of 1
[]
>>> test[-6:-1]
[1, 2]

如评论中所述,您的示例无论如何都是不匹配的; x[startplay:startplay+5]是一个长度为5的切片,x[1:5]是一个长度为4的切片。

答案 1 :(得分:0)

我和ShadowRanger在这一个。我看到该操作应该可以工作,并且可以在我下面创建的示例中工作。

def trial(x1, x2):
    array = [1,2,2,3,4,5,6,6,3,2,2,1,1,23,3,4,5,2,3,2,]
    new_array = array[int(x1):int(x2)]
    new_array2 = array[x1:x2]
    print(new_array2)
    print(new_array)
trial(1, 3)
[2, 2]
[2, 2]

确保您的列表能够首先执行操作...从硬性示例构建并引用documentation