Python 中列表、元组、集合与字典
- Python集合(数组)
- 列表
- 元组(Tuple)
- 集合(Set)
- 字典(Dictionary)
Python集合(数组)
Python编程语言中有四种集合数据类型:
列表(List)是一种有序和可更改的集合,允许重复的成员。
元组(Tuple)是一种有序且不可更改的集合。允许重复的成员。
集合(Set)是一个无序和无索引的集合,没有重复的成员。
字典(Dictionary)是一个无序,可变和有索引的集合,没有重复的成员。
列表
列表是一个有序且可更改的集合。在 Python 中,列表用方括号编写
实例:
thislist = ["apple", "banana", "cherry"]
print(thislist)
output:
['apple', 'banana', 'cherry']
访问项目
通过引用索引号来访问列表项:
实例:打印列表的第二项
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
output:
banana
遍历列表
实例:诸葛打印列表中的所有项目
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
output:
apple
banana
cherry
检查项目是否存在、列表长度、添加项目、删除等
clear() 方法清空列表:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
output:
[]
使用 list() 构造函数创建列表:
thislist = list(("apple", "banana", "cherry")) # 请注意双括号
print(thislist)
output:
['apple', 'banana', 'cherry']
元组(Tuple)
元组是有序且不可更改的集合。在 Python 中,元组是用圆括号编写的。
创建元组:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
output:
('apple', 'banana', 'cherry')
访问元组项目
可以通过引用方括号内的索引号来访问元组项目.
打印元组中的第二个项目:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
output:
banana
更改元组值
创建元组后,您将无法更改其值。元组是不可变的,或者也称为恒定的。
但是有一种解决方法。您可以将元组转换为列表,更改列表,然后将列表转换回元组。
把元组转换为列表即可进行更改
···
x = (“apple”, “banana”, “cherry”)
y = list(x)
y[1] = “kiwi”
x = tuple(y)print(x)
outputs:
(‘apple’, ‘kiwi’, ‘cherry’)
···
集合(Set)
集合是无序和无索引的集合。在 Python 中,集合用花括号编写
创建集合:
···
thisset = {“apple”, “banana”, “cherry”}
print(thisset)outpurs:
{‘apple’, ‘cherry’, ‘banana’}
···
访问项目
无法通过引用索引来访问 set 中的项目,因为 set 是无序的,项目没有索引。
但是可以使用 for 循环遍历 set 项目,或者使用 in 关键字查询集合中是否存在指定值。
添加项目
要将一个项添加到集合,请使用 add() 方法。
要向集合中添加多个项目,请使用 update() 方法
字典(Dictionary)
字典是一个无序、可变和有索引的集合。在 Python 中,字典用花括号编写,拥有键和值。
创建并打印字典:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
print(thisdict)
output:
{'brand': 'Porsche', 'model': '911', 'year': 1963}
访问项目
您可以通过在方括号内引用其键名来访问字典的项目:
获取 “model” 键的值:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
x = thisdict["model"]
print(x)
output:
911