Python集合(数组)
Python编程语言中有四种集合数据类型:
列表(list):是一种有序和可更改的集合,允许有重复成员的
元组(tuple):是一种有序且不可更改的集合,允许有重复成员的
集合(set):是一个无序和无索引的集合,没有重复成员的。
字典(dict):是一个无序、可变和有索引的集合,没有重复成员。
一、列表
1. 创建列表
>>> thislist = ["apple", "banana", "cherry"] >>> print (thislist)
2. 访问成员
['apple', 'banana', 'cherry'] >>> print(thislist[1]) banana >>> print(thislist[-1]) cherry
通过索引号访问列表项。
负的索引表示从末尾开始,-1表示最后一个成员,-2表示倒数第二个成员,依次类推。
>>> thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] >>> print(thislist[2:5]) ['cherry', 'orange', 'kiwi'] >>> print(thislist[-4:-1]) ['orange', 'kiwi', 'melon']
索引范围:可以指定范围的起点和终点来指定索引范围;指定范围后,返回值将是包含指定成员的新列表
注:第一项的索引为 0,搜索将从索引 2(包括)开始,到索引 5(不包括)结束
更改成员值:使用索引号
>>> thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]>>> thislist[1] = "huahua" >>> print(thislist) ['apple', 'huahua', 'cherry', 'orange', 'kiwi', 'melon', 'mango']
3. 遍历列表
使用for循环遍历列表
>>> thislist = ['apple', 'huahua', 'cherry', 'orange', 'kiwi', 'melon', 'mango'] >>> for x in thislist: ... print(x) ... apple huahua cherry orange kiwi melon mango
4. 检查成员是否存在使用in关键字
>>> thislist = ["apple", "banana", "cherry"] >>> if "apple" in thislist: ... print("Yes, 'apple' is in the fruits list") ... Yes, 'apple' is in the fruits list
5. 列表长度
使用len()方法
>>> thislist = ["apple", "banana", "cherry"] >>> print(len(thislist)) 3
6. 添加项目
使用append()方法
>>> thislist = ["apple", "banana", "cherry"] >>> thislist.append("orange") >>> print(thislist) ['apple', 'banana', 'cherry', 'orange']
要在指定的索引处添加项目,使用insert()方法
>>> thislist = ['apple', 'banana', 'cherry', 'orange'] >>> thislist.insert(1,"melon") >>> print(thislist) ['apple', 'melon', 'banana', 'cherry', 'orange']
7.删除项目
remove()方法删除指定的项目
>>> thislist = ['apple', 'banana', 'cherry', 'orange'] >>> thislist.remove("apple") >>> print(thislist) ['banana', 'cherry', 'orange']
pop()方法删除指定的索引(如果未指定索引,则删除最后一项)
>>> thislist = ['apple', 'banana', 'cherry', 'orange'] >>> thislist.pop() 'orange' >>> print(thislist) ['apple', 'banana', 'cherry']
del关键字删除指定的索引,也能完整的删除列表
>>> thislist = ['apple', 'banana', 'cherry', 'orange'] >>> del thislist[1] >>> print(thislist) ['apple', 'cherry', 'orange']
>>> thislist = ['apple', 'banana', 'cherry', 'orange'] >>> del thislist >>> print(thislist) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'thislist' is not defined
clear()清空列表
>>> thislist = ["apple", "banana", "cherry"] >>> thislist.clear() >>> print(thislist) []
8. 复制列表
通过键入list2 = list1 来复制列表,因为list2将只是对list1的引用,list1中所做的更改也将自动的在list2中进行。
>>> thislist = ["apple", "banana", "cherry"] >>> thislist2 = thislist >>> thislist2 ['apple', 'banana', 'cherry'] >>> thislist.append("melon") >>> thislist2 ['apple', 'banana', 'cherry', 'melon']
使用内置的list的copy()方法复制列表
>>> thislist = ["apple", "banana", "cherry"] >>> mylist = thislist.copy() >>> print(mylist) ['apple', 'banana', 'cherry'] >>> thislist.pop() 'cherry' >>> print(thislist) ['apple', 'banana'] >>> print(mylist) ['apple', 'banana', 'cherry']
使用内建方法list()方法复制列表
>>> thislist = ["apple", "banana", "cherry"] >>> mylist = list(thislist) >>> print(mylist) ['apple', 'banana', 'cherry']
9. 合并两个列表
最简单的方法是使用+运算符
>>> list1 = ["a", "b" , "c"] >>> list2 = [1, 2, 3] >>> list3 = list1 + list2 >>> print(list3) ['a', 'b', 'c', 1, 2, 3]
连接两个列表的方法,将list2中的所有项一个接一个的追加到list1中
>>> list1 = ["a", "b" , "c"] >>> list2 = [1, 2, 3] >>> for x in list2: ... list1.append(x) ... >>> print(list1) ['a', 'b', 'c', 1, 2, 3]
也可以使用extend()方法,将一个列表中的元素添加到另一个列表中
>>> list1 = ["a", "b" , "c"] >>> list2 = [1, 2, 3] >>> list1.extend(list2) >>> print(list1) ['a', 'b', 'c', 1, 2, 3]
10. list()构造函数
创建一个新的列表
>>> thislist = list(("apple", "banana", "cherry")) >>> print(thislist) ['apple', 'banana', 'cherry']
二、元组
1.创建元组
2.访问元组项目
>>> thistuple = ("apple", "banana", "cherry") >>> print(thistuple) ('apple', 'banana', 'cherry') >>> print(thistuple[1]) banana >>> print(thistuple[-1]) cherry >>> thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") >>> print(thistuple[2:5]) ('cherry', 'orange', 'kiwi') >>> print(thistuple[-4:-1]) ('orange', 'kiwi', 'melon')
3.更改元组值
注:创建元组后,无法更改其值。元组是不可变的,或者也称为恒定的。
但是有一种解决方法:可以将元组转换为列表,更改列表,然后将列表转换回元组
>>> x = ("apple", "banana", "cherry") >>> y = list(x) >>> y[1] = "kiwi" >>> x = tuple(y) >>> print(x) ('apple', 'kiwi', 'cherry')
4. 遍历元组
>>> thistuple = ("apple", "banana", "cherry") >>> for x in thistuple: ... print(x) ... apple banana cherry
>>> thistuple = ("apple", "banana", "cherry") >>> if "apple" in thistuple: ... print("yes,apple is in thistuple") ... else: ... print("no,apple is not thistuple") ... yes,apple is in thistuple
5. 创建有一个项目的元组
>>> thistuple = ("apple",) >>> print(type(thistuple)) <class 'tuple'> >>> thistuple = ("apple") >>> print(type(thistuple)) <class 'str'>
注:如需创建仅包含一个项目的元组,必须在该项目后添加一个逗号,否则 Python 无法将变量识别为元组
6. 元组方法
三、集合
集合用花括号编写
1. 创建集合
>>> thisset = {"apple", "banana", "cherry"} >>> print(thisset) {'apple', 'cherry', 'banana'}
2. 访问项目
无法使用索引访问set中的项目,因为set是无序的,没有索引
可以使用for循环遍历set项目,或者使用in关键字查询集合中是否存在指定值
>>> for x in thisset: ... print(x) ... apple cherry banana >>> print("apple" in thisset) True
3. 更改项目
集合一旦创建,无法更改项目。但是可以添加新项目
要将一个项目添加到集合,使用add()方法
要向集合中添加多个项目,使用update()方法
>>> thisset.add("orange") >>> print(thisset) {'apple', 'cherry', 'banana', 'orange'} >>> thisset.update(["orange", "mango", "grapes"]) >>> print(thisset) {'banana', 'grapes', 'apple', 'cherry', 'orange', 'mango'}
4. 获取set长度
使用len()方法确定set集合中有多少项目
>>> print(thisset) {'banana', 'grapes', 'apple', 'cherry', 'orange', 'mango'} >>> print(len(thisset)) 6
5. 删除项目
使用remove()或discard(),pop()方法
>>> thisset = {"apple", "banana", "cherry"} >>> thisset.remove("banana") >>> print(thisset) {'apple', 'cherry'} >>> thisset = {"apple", "banana", "cherry"} >>> thisset.discard("apple") >>> print(thisset) {'cherry', 'banana'} >>> thisset = {"apple", "banana", "cherry"} >>> thisset.pop() 'apple' >>> print(thisset) {'cherry', 'banana'}
clear()清空集合
>>> thisset = {"apple", "banana", "cherry"} >>> thisset.clear() >>> print(thisset) set()
del彻底删除集合
>>> del thisset >>> print(thisset) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'thisset' is not defined
6. 合并集合
使用union()方法返回包含两个集合中所有项目,也可使用update()方法将一个集合中所有的项目插入到另一个集合中。
>>> set1 = {"a", "b" , "c"} >>> set2 = {1,2,3,4} >>> set3 = set1.union(set2) >>> print(set3) {'a', 'b', 1, 2, 3, 4, 'c'}
>>> set1 = {"a", "b" , "c"} >>> set2 = {1,2,3,4} >>> set1.update(set2) >>> print(set1) {'a', 'b', 1, 2, 3, 4, 'c'}
注:union() 和 update() 都将排除任何重复项
7. set()构造函数
使用set()构造函数创建集合
>>> thisset = set(("apple", "banana", "cherry")) >>> print(thisset) {'apple', 'cherry', 'banana'}
四、字典
在python中,字典用花括号编写,拥有键和值
1. 创建字典
>>> thisdict = {"brand": "Porsche", "model": "911","year": 1963} >>> print(thisdict) {'model': '911', 'brand': 'Porsche', 'year': 1963}
2. 访问项目
通过引用其键名来访问字典项目
get()方法也可以获取特定的值
>>> x = thisdict["model"] >>> print(x) 911 >>> y = thisdict.get("year") >>> print(y) 1963
3. 更改值
通过引用其键名来更改特定项的值
>>> thisdict["year"] = 2019 >>> print(thisdict) {'model': '911', 'brand': 'Porsche', 'year': 2019}
4. 遍历字典
用for循环遍历字典
遍历字典时,返回值为字典的键
可以使用value()函数返回字典的值
使用items()函数遍历键和值
>>> print(thisdict) {'model': '911', 'brand': 'Porsche', 'year': 2019} >>> for x in thisdict: ... print(x) ... model brand year >>> for x in thisdict: ... print(thisdict[x]) ... 911 Porsche 2019 >>> for x in thisdict.values(): ... print(x) ... 911 Porsche 2019>>> for x,y in thisdict.items(): ... print(x,y) ... model 911 brand Porsche year 2019 >>> thisdict = {"brand": "Porsche", "model": "911","year": 1963} >>> if "model" in thisdict: ... print("yes,'model' is one of the keys in the thisdict dictionary") ... else: ... print("no") ... yes,'model' is one of the keys in the thisdict dictionary
5. 添加项目
通过使用新的索引键并为其赋值,可以将项目添加到字典
>>> thisdict = {"brand": "Porsche", "model": "911","year": 1963} >>> thisdict["color"]="red" >>> print(thisdict) {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963}
6. 删除项目
pop()方法删除具有指定键名的项
popitem()方法删除
del关键字删除具有指定键名的项目
del关键字也可以完全删除字典
clear()清空字典
>>> thisdict = {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> thisdict.pop("model") '911' >>> print(thisdict) {'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> thisdict = {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> thisdict.popitem() ('model', '911') >>> print(thisdict) {'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> del thisdict["color"] >>> print(thisdict) {'brand': 'Porsche', 'year': 1963} >>> del thisdict >>> print(thisdict) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'thisdict' is not defined >>> thisdict = {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> thisdict.clear() >>> print(thisdict) {}
7. 复制字典
使用copy()方法
使用dict()方法创建字典副本
>>> thisdict = {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> mydict = thisdict.copy() >>> print(mydict) {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> thisdict = {"brand": "Porsche", "model": "911","year": 1963} >>> mydict = dict(thisdict) >>> print(mydict) {'model': '911', 'brand': 'Porsche', 'year': 1963}
8. 嵌套字典
字典也可以包含很多字典
>>> myfamily = { "child1" : { "name" : "Phoebe Adele", "year" : 2002 }, "child2" : { "name" : "Jennifer Katharine", "year" : 1996 }, "child3" : { "name" : "Rory John", "year" : 1999 } }... ... ... ... ... ... ... ... ... ... ... ... ... >>> print(myfamily) {'child3': {'name': 'Rory John', 'year': 1999}, 'child1': {'name': 'Phoebe Adele', 'year': 2002}, 'child2': {'name': 'Jennifer Katharine', 'year': 1996}}
child1 = { "name" : "Phoebe Adele", "year" : 2002 } child2 = { "name" : "Jennifer Katharine", "year" : 1996 } child3 = { "name" : "Rory John", "year" : 1999 } myfamily = { "child1" : child1, "child2" : child2, "child3" : child3 }... ... ... >>> ... ... ... >>> ... ... ... >>> >>> ... ... ... ... >>> print(myfamily) {'child3': {'name': 'Rory John', 'year': 1999}, 'child1': {'name': 'Phoebe Adele', 'year': 2002}, 'child2': {'name': 'Jennifer Katharine', 'year': 1996}}
9. 字典方法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏