【问题标题】:Cannot remove the correct element from the index Python 3无法从索引 Python 3 中删除正确的元素
【发布时间】:2019-11-05 17:39:37
【问题描述】:

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

我的代码似乎可以工作,除非我输入一个整数,例如 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.x list indexing


【解决方案1】:

您正在使用 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/

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    相关资源
    最近更新 更多