使用pop
函数从定义的列表中读取值时,我没有得到所需的结果。
我的代码:
intList = [1, 5, 4, 9, 7, 2, 15]
def manipfunc(a):
j = a.index(2)
a.append(6.08)
a.remove(4)
a.insert(2,67)
g = a.pop(3)
print(a)
print(j, g)
manipfunc(intList)
在这里,g should be 7. but I'm getting g = 9
。
如果有人可以解释,那将是很棒的帮助.using pop function. Code and ouptput
让我们一步一步走:
a = [1, 5, 4, 9, 7, 2, 15]
j = a.index(2) #5
a.append(6.08) #[1, 5, 4, 9, 7, 2, 15, 6.08]
a.remove(4) #[1, 5, 9, 7, 2, 15, 6.08]
a.insert(2,67) #[1, 5, 67, 9, 7, 2, 15, 6.08]
现在我们到达g = a.pop(3)
和a[3] = 9
。
看起来对我来说是正确的输出。
当你进入功能
你打印的时候得到[1,5,67,7,2,15,6.08]然后得到5和9
你应该尝试弹出4而不是3。
intList = [1, 5, 4, 9, 7, 2, 15]
def manipfunc(a):
j = a.index(2)
a.append(6.08)
a.remove(4)
a.insert(2,67)
g = a.pop(4)
print(a)
print(j, g)
manipfunc(intList)
你应该小心qazxsw poi
或者你的错误可能在这里:a.remove(4)
,记住这条指令将值放在该索引中并更改数组其余部分的索引。
这是代码中每个步骤的结果:
a.insert(2,67)
输出:
intList = [1, 5, 4, 9, 7, 2, 15]
def manipfunc(a):
j = a.index(2)
print ("j: ",j)
a.append(6.08)
print ("intList: ",a)
a.remove(4)
print ("intList: ",a)
a.insert(2,67)
print ("intList: ",a)
g = a.pop(3)
print ("g: ",g)
manipfunc(intList)
现在你可以看到为什么j: 5
intList: [1, 5, 4, 9, 7, 2, 15, 6.08]
intList: [1, 5, 9, 7, 2, 15, 6.08]
intList: [1, 5, 67, 9, 7, 2, 15, 6.08]
g: 9
会得到结果。
pop函数将索引作为参数。
你可能误解了这个方法list.remove(x)
从列表中删除值等于x的第一个项目。如果没有这样的项,它会引发ValueError。来自python3.7 doc 9