python常见数据结构


—— 百度课程的搬运工
—— 推荐百度课程
—— 小白不对python进行深入研究,python不是小白的主要编程工具

字典

将键key映射到value的无序数据结构
值可以任何值:列表、函数、字符串、任何东西
key必须是不可变的:数字、字符串、元组

定义字典

#定义一个字典
webstersDict = {'person': 'a human being, whether an adult or child', 'marathon': 'a running race that is about 26 miles', 'resist': ' to remain strong against the force or effect of (something)', 'run': 'to move with haste; act quickly'}
webstersDict
#一个冒号连接一个key和一个value

访问字典

#访问一个值
#dictionary[key]
webstersDict['person']

更新字典

#更新字典
#直接定义键值和value,默认在末尾添加
webstersDict['shoe'] = 'an external covering for the human foot'
webstersDict
webstersDict['shoe']
webstersDict
#同时更新多个键值,更新重复的键时,覆盖掉,最终不会有重复的内容
webstersDict.update({'shirt': 'a long- or short-sleeved garment for the upper part of the body'
                     , 'shoe': 'an external covering for the human foot, usually of leather and consisting of a more or less stiff or heavy sole and a lighter upper part ending a short distance above, at, or below the ankle.'})
webstersDict

删除字典

del webstersDict['resist']
webstersDict
#删除键但同时可以返回值
count=storyCount.pop('the')
count

get()函数

#get()函数,如果键存在,则返回设定的值,如果不存在则为键设定默认值
storyCount.get('Michael')
storyCount.get('Michael',0)
storyCount.get('run',0)#虽然设定了默认值但是不会自动加入到字典中,只是返回设定的默认值
storyCount

#storyCount['run']#虽然设定了默认值但是不会自动加入到字典中,只是返回设定的默认值,所以是错误的
print(storyCount.get('run'))#如果不设定默认值返回的是None
print(storyCount.get('run'))#设定了默认值返回的就是默认值

打印字典

#遍历字典
#返回键
print(storyCount.keys())
#返回值
print(storyCount.values())
#迭代遍历键
for key in storyCount:
    print(key)
#迭代遍历键值
for key,value in webstersDict.items():#items表示类似集合的对象
    print(key,value)

元组

元组是一种序列,就想列表一样。元组和列表之间的区别在于,列表可变,元组不可更改。元组用括号,列表使用方括号

初始化

#元组初始化
#初始化空元组
emptyTuple=()
#使用元组函数初始化空元组
emptyTuple=tuple()
z=(3,7,4,2)#如果要创建仅包含一个值的元组,则需要在项目后面添加一个逗号
z

tup1=('michael',)#没有逗号就变成了字符串
tup1

访问元组中的值

从0开始

z[0]
#-1表示最后一个元素
animals=('lama','sheep','lama',48)
animals.index('lama')#索引默认出现的第一个位置
animals.count('lama')#计算出现的个数

切分元组

返回新元组(子集)

#切分元组
z[0:2]#表示下标0和1
z[:3]#表示下标0,1,2
z[-2:-1]#表示的不是最后一个元素,[-1]表示的是最后一个元素,现在表示的是-2这个元素,而不包括-1这个元素

遍历元组

for item in ('lama', 'sheep', 'lama', 48):
    print(item)

元组拆包

x, y = (7, 10);
print("Value of x is {}, the value of y is {}.".format(x, y))#{}表示要显示的元素

枚举

枚举函数返回一个元组,其中包含每次迭代的计数(从默认为0的开始)和迭代序列获得的值

friends = ('Steve', 'Rachel', 'Michael', 'Monica')
for index, friend in enumerate(friends):# 先定义一个元组然后,enumerate()为枚举函数
    print(index,friend)

元组与列表

元组可变,列表不可变
元组比列表更快,如果定义一组常量值,
元组可以作为字典键,列表不可以作为字典键
元组可以是集合中的值{},列表不可以是集合中的值

斐波那契数列

a,b = 1,1
for i in range(10):
    print("Fib(a): ", a, "b is: ", b)
    a,b = b,a+b  #直接按顺序赋值操作
发布了19 篇原创文章 · 获赞 0 · 访问量 1044

猜你喜欢

转载自blog.csdn.net/L_fengzifei/article/details/105157105