玖叶教程网

前端编程开发入门

python中元组,列表,字典,集合删除项目方式的归纳

九三,君子终日乾乾,夕惕若,厉无咎。

在使用python过程中会经常遇到这四种集合数据类型,今天就对这四种集合数据类型中删除项目的操作做个总结性的归纳。

  • 列表(List)是一种有序和可更改的集合。允许重复的成员。
  • 元组(Tuple)是一种有序且不可更改的集合。允许重复的成员。
  • 集合(Set)是一个无序和无索引的集合。没有重复的成员。
  • 词典(Dictionary)是一个无序,可变和有索引的集合。没有重复的成员。

一、元组

1、元组是不可更改的,因此您无法从中删除项目,但您可以完全删除元组(del)

thistuple = ("apple", "banana", "cherry")
del thistuple

print(thistuple)    # 这会引发错误,因为元组已不存在。

二、列表

有几种方法可以从列表中删除项目(remove,pop,del,clear)

1、remove() 方法删除指定的项目

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

2、pop() 方法删除指定的索引(如果未指定索引,则删除最后一项):

thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

3、del 关键字删除指定的索引:

thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

4、del 关键字也能完整地删除列表:

thislist = ["apple", "banana", "cherry"]
del thislist

5、clear() 方法清空列表:

thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

三、集合

有几种方法可以从集合中删除项目(remove,discard,pop,clear,del)

1、remove()

注释:如果要删除的项目不存在,则 remove() 将引发错误

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

2、discard()

注释:如果要删除的项目不存在,则 discard() 不会引发错误

thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

3、您还可以使用 pop() 方法删除项目,但此方法将删除最后一项。请记住,set 是无序的,因此您不会知道被删除的是什么项目。

pop() 方法的返回值是被删除的项目。

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)

4、clear() 方法清空集合

thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)

5、del 彻底删除集合;如果此时再打印这个集合,就会报错。

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)

四、字典

有几种方法可以从字典中删除项目(pop,popitem,clear,del)

1、pop() 方法删除具有指定键名的项目

thisdict =  {
    "brand": "Porsche",
    "model": "911",
    "year": 1963
}
thisdict.pop("model")
print(thisdict)

2、popitem() 方法删除最后插入的项目(在 3.7 之前的版本中,删除随机项目)

thisdict =  {
    "brand": "Porsche",
    "model": "911",
    "year": 1963
}
thisdict.popitem()
print(thisdict)

3、del 关键字删除具有指定键名的项目;del 关键字也可以完全删除字典(但是再打印这个字典时会报错)

thisdict =  {
    "brand": "Porsche",
    "model": "911",
    "year": 1963
}
del thisdict["model"]
print(thisdict)
thisdict =  {
    "brand": "Porsche",
    "model": "911",
    "year": 1963
}
del thisdict

print(thisdict) #this 会导致错误,因为 "thisdict" 不再存在。

4、clear() 关键字清空字典

thisdict =  {
    "brand": "Porsche",
    "model": "911",
    "year": 1963
}
thisdict.clear()
print(thisdict)

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言