首页 > 解决方案 > 无法从索引 Python 3 中删除正确的元素

问题描述

我正在尝试从整数中删除一个数字。

我的代码似乎可以工作,除非我输入一个整数,例如 8880888。

出于某种原因,使用上面的整数,当删除传递中间数字的索引时,它不会删除正确的索引。

    n = 8880888
    def question(n):
        newlist = [int(x) for x in str(n)] #coverting integer to list
        result = newlist[:]
        y = newlist[5]
        result.remove(y)
    return result

删除第 5 个元素时,它应该返回 888088。但是,我返回的是 880888。

标签: python-3.xlistindexing

解决方案


您正在使用 remove() 而不是 del 方法。如果您希望根据索引删除元素,您的代码应类似于:

n = [8, 8, 8, 0, 8, 8, 8]

#If you want to remove the 5th element:

del n[5]

请参考https://www.csestack.org/difference-between-remove-del-pop-python-list/


推荐阅读