第9篇,数据结构

数据结构,是用来存储一系列数据的集合。
在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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,695评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,569评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,130评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,648评论 1 297
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,655评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,268评论 1 309
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,835评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,740评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,286评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,375评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,505评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,185评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,873评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,357评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,466评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,921评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,515评论 2 359

推荐阅读更多精彩内容