数据结构,是用来存储一系列数据的集合。
在Python中,有四种内置的数据结构
- 列表
list
- 元组
tuple
- 字典
dictionary
- 集合
set
列表
列表是一种保存一系列有序项目的集合。项目的列表使用[ ]
来括起来,创建列表之后,我们可以对它之中的项目进行添加、移除、搜索操作。
列表是一种可变数据类型,这种类型是可以被改变的。
如下
# 创建和使用list
shopList = ['apple','banana','carrot','mango']
# 使用1
print("I have ",len(shopList), "items to purchase.")
# 获取列表中的元素
print('\n\n\n***********************************')
print("These items are:",end=' ')
for item in shopList:
print(item,end=' ')
# 往列表中添加一个元素
print('\n\n\n***********************************')
shopList.append("rice")
print('Now list is ',shopList)
# 对列表中的元素进行排序
print('\n\n\n***********************************')
shopList.sort()
print("Now list is ",shopList)
# 删除列表中的指定元素
print('\n\n\n***********************************')
del shopList[1]
print("Now list is ",shopList)
I have 4 items to purchase.
***********************************
These items are: apple banana carrot mango
***********************************
Now list is ['apple', 'banana', 'carrot', 'mango', 'rice']
***********************************
Now list is ['apple', 'banana', 'carrot', 'mango', 'rice']
***********************************
Now list is ['apple', 'carrot', 'mango', 'rice']
Process finished with exit code 0
元组Tuple
元组Tuple
的做用和列表差不多,但不同的是元组Tuple
和字符串一样,具有不可变性,也就是说,我们在声明一个元组之后,就不能再编辑和改变。
具体请看下面,元组的使用
# Tuple元组,可以使用()来显式的声明,来指定开始和结束
# 也可以隐式的声明
# Tuple做用类似于列表
# 但不同的是,它和字符串一样具有不可改变性,声明之后就不能再编辑和更改
tuple1 = ("item01","item02","item03")
print("Items number of tuple1 is ",len(tuple1))
tuple2 = tuple1,"item04","item05"
print("Items number of Tuple2 is ",len(tuple2))
print(tuple2)
print(tuple1[0])
print(tuple2[0][0])
print(len(tuple2)-1 + len(tuple2[0]) + len(tuple1))
Items number of tuple1 is 3
Items number of Tuple2 is 3
(('item01', 'item02', 'item03'), 'item04', 'item05')
item01
item01
8
Process finished with exit code 0
和列表一样,元组也可以通过索引值的方式来访问其中的元素。
创建包含0个或者1个元素的元组,请看下面的例子
# 创建一个空元组
tempTuple = ()
print("Length of tmpTuple is ",len(tempTuple))
# 创建只包含一个元素,比如 3 的元组
# 不能直接使用(3)的形式,因为在Python中不确定(3)是一个被括号包括的对象,还是一个元组。
# 所以在元组中,声明一个只有一个元素的元组,必须用(ele,)的形式
oneTuple = (3,)
print("Length of OneTuple is ",len(oneTuple),"items are ",oneTuple)
for item in oneTuple:
print(item)
字典Dictionary
关于字典的创建和使用,请看下面的代码
# 字典 以dictionary={key:value,...}的形式创建
infoDictionary = {
'name':'Xcode',
'age':18,
'address':'xx_xxx+xxxx_xqwer'
}
print(infoDictionary)
# 通过key访问字典的某一个值
print(infoDictionary['name'] + infoDictionary['address'])
# 删除一个key对应的值
del infoDictionary['address']
print(infoDictionary)
# 通过key添加新的值
infoDictionary['Tel'] = '19999999999'
print('The new info are ',infoDictionary)
# 判断一个值是否存在于字典中
if 'Tel' in infoDictionary:
print(infoDictionary['Tel'])
# 获取字典中所有的key-value对
print("All key-value are:")
for item in infoDictionary.items():
print("\n",item)
# 获取字典中所有的key
print("All keys are :")
for itemKey in infoDictionary.keys():
print(itemKey)
# 获取字典所有的value
print("ALL VALUE ARE :")
for itemValue in infoDictionary.values():
print(itemValue)
{'name': 'Xcode', 'age': 18, 'address': 'xx_xxx+xxxx_xqwer'}
Xcodexx_xxx+xxxx_xqwer
{'name': 'Xcode', 'age': 18}
The new info are {'name': 'Xcode', 'age': 18, 'Tel': '19999999999'}
19999999999
All key-value are:
('name', 'Xcode')
('age', 18)
('Tel', '19999999999')
All keys are :
name
age
Tel
ALL VALUE ARE :
Xcode
18
19999999999
Process finished with exit code 0
序列
列表 、元组、 字符串都可以看做是序列的一种。序列的主要功能就是资格测试(in 与 not in的表达式)和索引操作。通过这两个主要功能,我们可以直接获取序列中的特定项目。
通过切片运算,我们也能过获取序列中的某段切片,也居室某一部分。
请看下面的代码
# 序列
shopList = ['apple','banana','carrot','mango']
name = 'MyShopList'
print('******************************************************************')
# 索引/下标的方式来访问
print('Item0 is ',shopList[0])
print('Item1 is ',shopList[1])
print('Item2 is ',shopList[2])
print('Item3 is ',shopList[3])
print('Item-1 is ',shopList[-1])
print('Item-2 is ',shopList[-2])
print('Item-2 is ',shopList[-3])
print('Item-3 is ',shopList[-4])
print('name 0 is ',name[0])
print('name -3 is ',name[-3])
print('******************************************************************')
# 通过切片方式访问
print(shopList[1:3])
print(shopList[0:2])
print(shopList[0:-1])
print(name[0:3])
print(name[1:4])
print(name[:])
print(name[:-1])
print('******************************************************************')
# 切片操作中提供第三个参数,这个参数为切片操作的步长(Step),默认值为1
print(name[::])
print(name[::1])
print(name[::2])
print(name[::3])
******************************************************************
Item0 is apple
Item1 is banana
Item2 is carrot
Item3 is mango
Item-1 is mango
Item-2 is carrot
Item-2 is banana
Item-3 is apple
name 0 is M
name -3 is i
******************************************************************
['banana', 'carrot']
['apple', 'banana']
['apple', 'banana', 'carrot']
MyS
ySh
MyShopList
MyShopLis
******************************************************************
MyShopList
MyShopList
MSoLs
MhLt
Process finished with exit code 0
有几点需要注意
在切片运算
[startIndex:endIndex]
中,得到结果包括startIndex
对应的对象,但不包括endIndex
对应的对象。请参考print(name[1:4])
的输出结果
[:]
返回的是整个序列,请参考print(name[:])
的输出结果
在切片运算中也可以使用负数位置,如
print(name[:-1])
返回的结果是一个不包含序列最后一个项目的新序列MyShopLis
切片操作中提供第三个参数,这个参数为切片操作的步长(
Step
),默认值为1。请参考
print(name[::])
、print(name[::1])
、print(name[::2])
、print(name[::3])
的输出结果。
集合
集合(Set
)是简单对象的无序集合(Collection
),当集合中的项目比起次序或者其出现次数更重要时我们使用集合。
请看下面代码
# 创建一个集合
# 方式一 :shopList = set(['Apple','Banana','carrot'])
# 方式二
shopList = {'Apple','Banana','carrot'}
print(shopList)
# 判断某一元素或对象是否在集合中
print('xxx' in shopList)
print('Apple' in shopList)
# 复制一个集合并赋值给新的名称
newShopList = shopList.copy()
print(newShopList)
# 添加新元素
# 注意copy()的作用性
newShopList.add('Mango')
print(shopList,'***',newShopList)
# 移除一个元素
if 'Apple' in shopList:
shopList.remove('Apple')
print(shopList)
# 求两个集合的共有的元素,生成一个新的集合
print(shopList & newShopList)
print(shopList.intersection(newShopList))
{'Banana', 'carrot', 'Apple'}
False
True
{'Banana', 'carrot', 'Apple'}
{'Banana', 'carrot', 'Apple'} *** {'Banana', 'Mango', 'carrot', 'Apple'}
{'Banana', 'carrot'}
{'Banana', 'carrot'}
{'Banana', 'carrot'}
Process finished with exit code 0
引用
# 引用
# 党创建一个对象,并且复制给一个变量时,变量只会查阅(refer)该对象,并且不会代表对象本身
# 也就是说,变量只是指向计算机内存中创建了该对象的那一部分,这种情况,叫做将变量名绑定(binding)给该对象
# 如下shopList和myList指向同一个对象
shopList = ['Apple','Banana','Carrot','Mango']
myList = shopList
# 从下面两个输出结果,来验证shopList和myList指向同一个对象
del shopList[0]
print('shopList is ',shopList)
print('myList is',myList)
print('\n\n')
# 通过切片操作[:]生成一份完整的切片来制作一份列表的副本
# 因为赋值操作不会生成一份副本,而切片操作可以创建一份副本
myList = shopList[:]
del myList[0]
print('shopList is ',shopList)
print('myList is',myList)
shopList is ['Banana', 'Carrot', 'Mango']
myList is ['Banana', 'Carrot', 'Mango']
shopList is ['Banana', 'Carrot', 'Mango']
myList is ['Carrot', 'Mango']
Process finished with exit code 0
字符串的更多操作
# 字符串的更多操作
myString = 'MyStringIsNothing'
# 判断字符串是否以某一字符或字符串做开头
if myString.startswith('My'):
print('myString is contains ','My')
# 判断字符串是否包含某一字符或字符串
if 'ing' in myString:
print('myString is contains ','ing')
# 定位字符串中给定的子字符串的位置
# 如果找不到相应的字符串,返回-1
if myString.find('ing') != -1:
print("myString is contains 'ing' ")
# 联结(join)操作,B.join(A),,将B作为A中每一项目元素的连接符
testList = ['Apple','Banana','Carrot']
decLine = '-**-'
print(decLine.join(testList))
myString is contains My
myString is contains ing
myString is contains 'ing'
Apple-**-Banana-**-Carrot
Process finished with exit code 0