如何不通过索引删除数组指定元素?调用pop方法按名称删除失败咨询
Python列表删除指定元素的方法
首先明确:list.pop()方法仅支持传入整数类型的索引值,不能直接用元素名称,这就是你代码执行失败的原因——你给pop()传了字符串"Holly",但它需要整数索引参数。
如果要通过元素名称删除列表中的指定元素,有两种常用方法:
1. 使用list.remove()方法
这是最直接的方式,remove()会删除列表中第一个匹配指定值的元素:
Attendance = ['Holly','James','Barry','John','Lewy'] Present = input("Is Holly present?") if Present == "N": # 先判断元素是否存在,避免报错 if "Holly" in Attendance: Attendance.remove("Holly") print(Attendance[0])
注意:如果列表中没有该元素,remove()会抛出ValueError,建议先通过in关键字判断元素是否存在。
2. 先获取索引再用pop()删除
如果你一定要用pop(),可以先通过list.index()获取元素的索引,再传入pop():
Attendance = ['Holly','James','Barry','John','Lewy'] Present = input("Is Holly present?") if Present == "N": if "Holly" in Attendance: idx = Attendance.index("Holly") Attendance.pop(idx) print(Attendance[0])
同样,index()在找不到元素时会报错,所以需要先做存在性检查。
内容的提问来源于stack exchange,提问作者Shaneb7102
相关产品推荐
相关产品推荐

