Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据索引删除列表中的项_Python_List - Fatal编程技术网

Python 根据索引删除列表中的项

Python 根据索引删除列表中的项,python,list,Python,List,我正在尝试解决一个小难题,我需要删除13号,然后在列表中删除后面的数字(这是一个关于CodingBat的练习) 这是我的代码: n = [1, 2, 3, 13, 5, 13] for i in n: if i == 13: n.remove(i) and n.remove(n.index(i+1)) print n 所需输出:[1,2,3] 但是,我的错误输出是:[1,2,3,5]#13(即5)之后的项目没有被删除 我原以为这个n.remove(n.index(

我正在尝试解决一个小难题,我需要删除13号,然后在列表中删除后面的数字(这是一个关于CodingBat的练习)

这是我的代码:

n = [1, 2, 3, 13, 5, 13] 

for i in n:
    if i == 13:
        n.remove(i) and n.remove(n.index(i+1))

print n
所需输出:
[1,2,3]

但是,我的错误输出是:
[1,2,3,5]#13(即5)之后的项目没有被删除

我原以为这个
n.remove(n.index(I+1))
会删除13之后的项,但事实并非如此

在你的
n.remove()
之后,你的数组是
[1,2,3,5,13]
,所以
n.remove(n.index(i+1))
指的是13不到5

在你的
n.remove()
之后,你的数组是
[1,2,3,5,13]
,所以
n.remove(n.index(i+1))
指的是13不到5

这应该有效:

n = [1, 2, 3, 13, 5, 13] 

for i in n:
    if i == 13:
        n.remove(n[n.index(i)+1]) # remove the element after `i` first
        n.remove(i) 

print n
问题的while循环:

n = [1, 2, 3, 13, 5, 13] 

i = 0
while i < len(n):
    if n[i] == 13:
        n.pop(i)
        if i < len(n):
            n.pop(i)
    else:
        i = i + 1

print n

# [1, 2, 3]
n=[1,2,3,13,5,13]
i=0
而i
这应该可以:

n = [1, 2, 3, 13, 5, 13] 

for i in n:
    if i == 13:
        n.remove(n[n.index(i)+1]) # remove the element after `i` first
        n.remove(i) 

print n
问题的while循环:

n = [1, 2, 3, 13, 5, 13] 

i = 0
while i < len(n):
    if n[i] == 13:
        n.pop(i)
        if i < len(n):
            n.pop(i)
    else:
        i = i + 1

print n

# [1, 2, 3]
n=[1,2,3,13,5,13]
i=0
而i
删除
13
后,
5
的索引是什么?迭代时不要更改列表的长度。
n.index(x)
被定义为“返回最小的
i
,以便
i
是数组中第一次出现的
x
的索引。”使用
关键字是错误的。不能使用它将命令串在一行上<代码>和
是逻辑运算符
和&
的替换,因此,您尝试比较两个无返回操作,而不是执行two@m_callens他还混合使用
i
作为迭代值和index@m_callens事实上,这将很好地工作,虽然它被认为是一个有点黑客。在你删除
13
之后,
5
的索引是什么?迭代时不要更改列表的长度。
n.index(x)
被定义为“返回最小的
i
,以便
i
是数组中第一次出现的
x
的索引。”使用
关键字是错误的。不能使用它将命令串在一行上<代码>和
是逻辑运算符
和&
的替换,因此,您尝试比较两个无返回操作,而不是执行two@m_callens他还混合使用
i
作为迭代值和index@m_callens实际上,这将很好地工作,尽管这被认为是一个小问题。
如果i==13
-->
i
被用作一个值……
n.remove(i)
-->
i
用作索引…问题?;)@同化器
n.remove(i)
将删除列表中具有值
i
的第一个元素<代码>i
用作值而不是索引。啊,nvm,你说得对:P@Psidom谢谢你的意见!但是,当我运行此程序时,它会输出
[1,2,3,13]
,可能是因为这篇文章,如果I==13
-->
I
用作值,则您的问题会被标记为
的重复项。…
n.remove(I)
-->
I
用作索引@同化器
n.remove(i)
将删除列表中具有值
i
的第一个元素<代码>i
用作值而不是索引。啊,nvm,你说得对:P@Psidom谢谢你的意见!但是,当我运行此程序时,它会输出
[1,2,3,13]
,可能是因为您的问题被标记为的帖子的副本