弹出功能输出错误

时间:2019-03-14 01:45:04

标签: python pop

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

5 个答案:

答案 0 :(得分: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

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

答案 1 :(得分: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

打印a时,您会得到[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)

您应该小心a.remove(4)

或者您的错误可能在这里:a.insert(2,67),请记住此指令将值放入该索引并更改数组其余部分的索引。

答案 2 :(得分:0)

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

include ../header.php

输出:

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 出现在结果中了。

答案 3 :(得分:0)

pop函数将index作为参数。

答案 4 :(得分:-1)

您可能误解了此方法 list.remove(x)

从列表中删除值等于x的第一项。如果没有这样的项目,它将引发ValueError。 来自python3.7 doc https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks

相关问题