弹出功能输出错误

问题描述 投票:-1回答:5

使用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

python pop
5个回答
2
投票

让我们一步一步走:

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

看起来对我来说是正确的输出。


0
投票

当你进入功能

  1. j = 4
  2. 你在数组的末尾追加6.08
  3. 之后你删除4并且向量变为[1,5,9,7,2,15,6.08]
  4. 在位置2插入67,向量变为:[1,5,67,9,7,2,15,6.08]
  5. 你弹出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),记住这条指令将值放在该索引中并更改数组其余部分的索引。


0
投票

这是代码中每个步骤的结果:

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 会得到结果。


0
投票

pop函数将索引作为参数。


-1
投票

你可能误解了这个方法list.remove(x)

从列表中删除值等于x的第一个项目。如果没有这样的项,它会引发ValueError。来自python3.7 doc 9

© www.soinside.com 2019 - 2024. All rights reserved.