import timeit
#字典是将键(key)映射到值(value)的无序数据结构。
#值可以是任何值(列表,函数,字符串,任何东西)。键(key)必须是不可变的,例如,数字,字符串或元组
#比如用列表当做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['marathon']
# 更新字典 添加key和value
webstersDict['shoe'] = 'an external covering for the human foot'
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.'})
# 去除字典中的某个key和对应的value
del webstersDict['resist']
storyCount = {'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
# 使用get()方法返回给定键的值 指定当这个key不存在时返回0,不指定默认为None
print(storyCount.get('Michael',0))
#删除键同时可以返回该键对应的值
count=storyCount.pop('the')
#遍历字典
print(storyCount.keys())
print(storyCount.values())
for key in storyCount:
print(key)
for key, value in webstersDict.items():
print(key, value)
# 元组是一种序列,就像列表一样 元组和列表之间的区别在于,元组不能更改(不可变)
# 元组使用括号,而列表使用方括号
# 如果创建仅包含一个值的元组,则需要在项目后面添加一个逗号
tup1 = ('Michael',)
z = (3, 7, 4, 2)
# 元组是不可变的,这意味着在初始化元组之后,不可能更新元组中的单个项
# 但是可以像字符串一样 + *得到新的元组,可以像列表一样遍历元组
# enumerate()函数返回一个元组,其中包含每次迭代的计数(从默认为0的开始)和迭代序列获得的值
friends = ('Steve', 'Rachel', 'Michael', 'Monica')
list1=[5,8,10,3]
for index, list1 in enumerate(list1):
print(index,list1)
for index, friend in enumerate(friends):
print(index,friend)
# (1)元组比列表更快,如果定义一组常量值,优先选用元组
# (2)元组可以用作字典键 列表不可以用作字典键
# (3)元组可以是集合中的值 列表不可以是集合中的值
# 用timeit为代码计时,下面代码为每个方法运行100万次,并输出所花费的总时间(单位:s)
print('Tuple time: ', timeit.timeit('x=(1,2,3,4,5,6,7,8,9,10,11,12)', number=1000000))
print('List time: ', timeit.timeit('x=[1,2,3,4,5,6,7,8,9,10,11,12]', number=1000000))
bigramsTupleDict = {('this', 'is'): 23,
('is', 'a'): 12,
('a', 'sentence'): 2}
# 集合
graphicDesigner = {('this', 'is'),
('is', 'a'),
('a', 'sentence')}
# 输出斐波那契数列 i从0开始
a,b = 1,1
for i in range(10):
print("i:",i,"Fib(a): ", a, "b is: ", b)
a,b = b,a+b
python学习代码片段(二):字典、元组
猜你喜欢
转载自blog.csdn.net/qq_42878057/article/details/105182835
今日推荐
周排行