for循环和字典预习
Posted startl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了for循环和字典预习相关的知识,希望对你有一定的参考价值。
print("*" *8)
for a in range(1,9):
print(a,end="")
#1-9的奇数
print()
for a in range(1,10,2):
print(a,end="")
#1-100的和
print()
sum=0
for a in range(1,101):
sum+=a
print(sum)
print()
#字典及字典的常用功能
D={
‘k1‘:‘v1‘,
‘k2‘:‘v2‘,
‘k3‘:‘v3‘,
}
print("D的类型是:",type(D)) # <class ‘dict‘>
print(len(D))# 3
print(D.keys())#dict_keys([‘k1‘, ‘k2‘, ‘k3‘])
print(D.values())#dict_values([‘v1‘, ‘v2‘, ‘v3‘])
print(D.items())# dict_items([(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘), (‘k3‘, ‘v3‘)])
print("-------------------")
F={
‘m1‘:[1,2,3,4],
1:2,
‘m2‘:‘v2‘,
‘m3‘:(1,2,3),
‘m4‘:{
‘name‘:‘vae‘,
‘age‘:18,
}
}
print("F的类型是:",type(F))#<class ‘dict‘>
print(len(F))# 5
print(F.keys())#dict_keys([‘m1‘, 1, ‘m2‘, ‘m3‘, ‘m4‘])
print(F.values())#dict_values([[1, 2, 3, 4], 2, ‘v2‘, (1, 2, 3), {‘name‘: ‘vae‘, ‘age‘: 18}])
print(F.items())#dict_items([(‘m1‘, [1, 2, 3, 4]), (1, 2), (‘m2‘, ‘v2‘), (‘m3‘, (1, 2, 3)), (‘m4‘, {‘name‘: ‘vae‘, ‘age‘: 18})])
print(‘#获取值的方式1‘)
print(F[1])# 2
print(F["m1"])#[1, 2, 3, 4]
print(F[‘m2‘])#v2
print(F[‘m3‘])#(1, 2, 3)
print(F["m4"])#{‘name‘: ‘vae‘, ‘age‘: 18}
# print(F["m5"]) KeyError: ‘m5‘
print(‘#获取值的方式2‘)
print(F.get(‘m1‘))#[1, 2, 3, 4]
print(F.get(‘m2‘))#v2
print(F.get("m3"))# (1, 2, 3)
print(F.get("m4"))#{‘name‘: ‘vae‘, ‘age‘: 18}
print(F.get(1))# 2
print(D.get(‘m6‘))#无值也不报错 None
print(D.get(‘m6‘,"True"))#True
print(‘#获取值的方式3‘)#此方法会修改字典
print(F.setdefault(‘m1‘))#[1, 2, 3, 4]
print(F.setdefault(‘m7‘))#None
print(F)#{‘m1‘: [1, 2, 3, 4], 1: 2, ‘m2‘: ‘v2‘, ‘m3‘: (1, 2, 3), ‘m4‘: {‘name‘: ‘vae‘, ‘age‘: 18}, ‘m7‘: None}
以上是关于for循环和字典预习的主要内容,如果未能解决你的问题,请参考以下文章