python-3.x - 无法从索引 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。
解决方案
您正在使用 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/
推荐阅读
- c# - 连续单击时不显示列表视图上下文菜单
- python-3.x - Python 脚本处理并生成 html 格式的结果。我希望它使用 WSGI 在网络上发布
- c# - EF Core IdentityUser 与业务模型存在多对多关系,如何使用 .Include().ThenInclude()?
- java - 如何从二维数组(java)中打印出奇数索引元素?
- python - Scrapy 仅返回字母列表中每个字母的第一项
- ios - UITextContentType 用户名正在使用电子邮件地址,但不是用户名
- java - 使用 select 和 option 标签在 jsp 中插入数据
- html - 如何在 Microsoft Edge 的 CSS 中将宽度设置为可用填充?
- c# - 压缩多个 csv 的 SSIS 脚本任务失败 - 当前上下文中不存在名称 zipfile
- javascript - 使用 javascript 保存 cookie 时出现 403 错误