如果这个函数从-2位置开始,它应该打印115,43。
def increment(nums):
t = (nums[-2:-4:-2 ])
print(t)
print(increment([43, 90, 115, 500])) 但是,这段代码的输出只有115,为什么呢?
发布于 2022-08-20 05:26:52
如果使用[-2:-4:-1],可以看到结果是[115, 90],而不包括43。这是因为python范围不包括第二个界限。
如果您想包括43,应该使用[-2:-5:-2]。结果将是[115, 43]
发布于 2022-08-20 05:40:03
试试这段代码,
def increment(nums):
print(nums[-2:-5:-2]) # output: [115, 43]
increment([43, 90, 115, 500])python切片:slice(start, end, step)
当您给nums[-2:-4:-2 ]时,python将从115开始,将2位置跳转到left并到达43,但您已经将结束设置为90 (-4 will go upto -3 position, not 43)
所以,我把end index改成了-5
https://stackoverflow.com/questions/73424262
复制相似问题