在Python数组中,我需要知道(,如果可能)如何通过名称删除数组元素,而不知道数组中元素的索引。
所以,如果我定义了这个数组
usernames = ["Billy", "Bob", "Apple"]
然后我们将有三个数组元素。
Billy , Bob 和 Apple 。
然后,如果我有这个代码
# Deleting the element
def delete_username():
to_delete = raw_input("Username to remove:")
# (Code to delete by element name)
我需要知道如何通过它的名称删除数组中的元素。
例如,如果用户输入了" Billy,"并且该程序不知道数组中Billy的索引,我们如何从数组中删除Billy,只知道它的名字?
答案 0 :(得分:5)
您也可以使用remove
usernames = ["Billy", "Bob", "Apple"]
if "Billy" in usernames:
usernames.remove("Billy")
# usernames = ["Bob", "Apple"]
答案 1 :(得分:4)
您可以使用remove()
方法删除元素。在尝试删除之前检查列表中是否存在所需元素,因为如果列表中不存在该元素,则会引发ValueError
。
if to_delete in usernames:
usernames.remove(to_delete)
答案 2 :(得分:0)
if to_delete in usernames:
usernames.pop(usernames.index(to_delete))
基本上就是这样。
答案 3 :(得分:0)
def remove_by_name(name):
if name in usernames:
usernames.remove(name)
仅删除第一个匹配项,如果需要所有元素,请修改上面的示例。