Python python基础02

一、字典

1、字典的使用

(1)定义:在Python中,字典是一系列键—值对。每个键都与一个值相关联,可以使用键来访问与其相关联的值。与键相关联的值可以是数字、字符串、列表甚至字典。(事实上,可将任何Python对象放进字典当中。)在python中,字典用放在花括号内一系列键—值对表示。

例如:

zhangsan={'height':183,'kg':80}
print(zhangsan['height'])
print(zhangsan['kg'])
#输出为183,80

键—值对是两个相关联的值。指定键时,Python将返回与之相关联的值,键和值之间用冒号分隔,而键—值对之间使用逗号分隔。在字典中,键—值对的储存没有限制。

在上述zhangsan的字典中,height与kg为键,183和80为对应的值。

(2)访问字典中的值。

要访问字典中的值,可以依次指定字典名和放在方括号内的键。

字典中的值可以被任意使用(类似于变量的使用),使用时指定字典名和方括号内的键即可使用。

(3)添加键-值对

01、字典是一种动态结构,可随时在其中添加键-值对。要添加键-值对,可依次指定字典名、用方括号括起来的键和相关联的值。。

格式:

字典名 [ '键名‘ ] = 值

zhangsan={'height':183,'kg':80}
print(zhangsan['height'])
print(zhangsan['kg'])
#输出为183,80
zhangsan['facevalue']=10
zhangsan['gfname']="wangmazi"
print(zhangsan)
#输出为{'height':'183','kg':80,'facevalue':10,'gfname':'wangmazi'}

注意:键-值对的排列顺序可能和添加顺序不同,python不关心添加顺序,只关心键-值对之间的关联关系。

(4)字典的另一种定义

先创建一个空字典,再向其中添加键-值对。

例如:

lisi={}
lisi['math']=100
lisi['history']=90
print(lisi)
#输出为{'math':100,'history':90}

(5)修改字典中的值

修改格式:

字典名 [ '键名' ] = 新值

lisi={}
lisi['math']=100
lisi['history']=90
print(lisi)
#输出为{'math':100,'history':90}
lisi['math']=44
print(lisi['math'])
#44

(6)删除键-值对

使用del语句,格式如下:

del 字典名  [ '键名' ]

lisi={}
lisi['math']=100
lisi['history']=90
print(lisi)
#输出为{'math':100,'history':90}
lisi['math']=44
print(lisi['math'])
#44
del lisi['history']
print(lisi)
#输出{'math':44}

注意:删除的键-值对将永久消失。

(7)由类似对象组成的字典

确定需要使用多行来定义字典时,在输入花括号后按回车键并在下一行缩进四个空格,指定第一个键-值对,并在他后面加上一个逗号。此后每按一次回车键,编译器都会自动进行缩进操作。

例如:

wangwu_score={
    'math':90,
    'history':87,
    'English':64.5,
}

注意:最好在最后一对键-值对后添加逗号,方便以后键-值对的添加。

2、遍历字典

(1)遍历所有的键值对

要想遍历字典,需要定义两个变量用来分别存储键和值并使用for循环。for语句的第一个部分用来定义两个变量,第二个部分包括字典名和items()方法,它会返回一个键-值对列表。接下来,for循环将依次将每一对键-值对存储到两临时变量当中。

例如:

wangwu_score={
    'math':90,
    'history':87,
    'English':64.5,
}
for s1,s2 in wangwu.items():
    print("\ns1:"+s1)
    print("\ns2:"+s2)
#输出结果为
#s1: math 
#s2: 90
#s1: history
#s2: 87
#s1: English
#s2: 64.5

注意:遍历字典时键-值对的返回顺序可能和存储数据不同。Python不关心顺序,只跟踪键-值对的关联关系。

(2)遍历字典中的键

01、简单遍历:使用方法keys()

例如:

wangwu_score={
    'math':90,
    'history':87,
    'English':64.5,
}
for subject in wangwu.keys(): 
    print(subject.title())
#输出为:
#Math
#History
#English

注意:遍历字典时会默认遍历所有的键,如果省略keys()方法,输出的结果一样。

方法keys()并非只能用于遍历,实际它返回了一个列表这个列表中包含所有的键。

例如:

wangwu_score={
    'math':90,
    'history':87,
    'English':64.5,
}
chinese =['math','history']
for subject in wangwu_score.keys():
    if subject in chinese:
        print('wangwu.title() like'+wangwu_score[sunject]+',because Learn English is not chinese?!')
#输出:
#Wangwu like math ,because Learn English is not chinese?!
#Wangwu like history ,because Learn English is not chinese?!
if'sport' not in wangwu_score.keys():
    print("You only konw learning")
#输出:You only konw learning

02、按顺序遍历字典中的所有键

要以特定的顺序返回元素,可使用函数sorted()来获得按特定的顺序排列的键列表的副本。

wangwu_score={
    'math':90,
    'history':87,
    'English':64.5,
}
for subject in sorted(wangwu_score.keys()):
    print('wangwu.title(),your'+wangwu_score[subject]+'is good!')
#输出:
#Wangwu,your English is good!
#Wangwu,your history is good!
#Wangwu,your math is good!

(3)遍历字典中所有的值

使用方法values()可以遍历字典中所有的值,如果要输出的列表中要求没有重复可调用set()函数。

wangwu_score={
    'math':90,
    'history':87,
    'English':64.5,
    'computer':64.5,
}
for score in wangwu_score.values():
    print(score)
#输出: 90 87 64.5 64.5 
for score in set(wangwu_score.values()):
    print(score)
#输出 90 87 64.5

3、嵌套

(1)定义:将一系列字典存储在列表中,或者将列表作为值存储在字典中,这被称为嵌套。

(2)字典中存储列表

先创建字典,然后将字典名存储在列表当中,输出时使用for循环进行打印,将打印出这三个字典。

例如:

zhangsan_s1={'math':90,'history':70}
lisi_s2={'math':87,'history':65}
wangmaizi_23={'math':76,'history':98}
nanme_s=[zhangsan,lisi,wangmaizi]
for name in name_s:
    print(name)
#输出为:
#{'math':90,'history':70}
#{'math':87,'history':65}
#{'math':76,'history':98}

字典列表的综合应用:

random=[]
for random1 in range(30):
    new_random={'what':"Love",'number':3000}
    random.append(new_random)
for ran in random[:5]:
    print(ran)
print("\n...")
print("Total is"+str(len(random)))
for ran in random[0:3]:
    if ran['what']=='Love':
        ran['what']='loving'
        ran['number']='1'
for rans in random[:3]:
    print(rans)
#输出结果为:
#{'what': 'Love', 'number': 3000}
#{'what': 'Love', 'number': 3000}
#{'what': 'Love', 'number': 3000}
#{'what': 'Love', 'number': 3000}
#{'what': 'Love', 'number': 3000}

#...
#Total is30
#{'what': 'loving', 'number': '1'}
#{'what': 'loving', 'number': '1'}
#{'what': 'loving', 'number': '1'}

(3)列表中存储字典:

当需要在字典当中将一个键关联到多个值时,都可以在字典中嵌套一个列表。

例如:

favorite_language = {
    'zhangsan': ['python', 'c'],
    'lisi': ['java', 'python'],
    'wangmazi': ['c#'],
    'wangwu': ['c++'],
    'wangerxiao': ['java', 'c'],
}

for name, languages in favorite_language.items():
    if len(languages)==2:
        print(name.title()+" favorite languages are :")
        for language in languages:
            print(language)
    else:
        for language in languages:
            print(name.title()+" favorite is :"+language)
#输出为:
#Zhangsan favorite languages are :
#python
#c
#Lisi favorite languages are :
#java
#python
#Wangmazi favorite is :c#
#Wangwu favorite is :c++
#Wangerxiao favorite languages are :
#java
#c

(4)字典中存储字典

将字典中的键改为字典名,并存储相应的值。

例如:

name_scores={
    'zhangsan':{
        'math':90,
        'history':87,
        'pass':"yes",
    },
    'lisi': {
        'math': 52,
        'history': 61,
        'pass': "no",
    }
}
for name,name_info in name_scores.items():
    print(name.title()+"\t"+str((name_info['math']+name_info['history'])/2))
    avg=((name_info['math']+name_info['history']))/2
    if(avg<60):
        print("no")
    else:
        print("yes")
#输出为:
#Zhangsan	88.5
#yes
#Lisi	56.5
#no

二、用户输入和while循环

1、函数input()的工作原理

(1)定义:函数inpu()让程序暂停运行,等待用户输入一些文本。获取用户输入后,python将其存储到一个变量当中。函数input存储一个参数:即要向用户显示的提示或说明。

例如:

message=input("I Love You!\n")
print("I love "+message+"\tthree thousand!")
#I Love You!
#输入money
#显示I love money	three thousand!

(2)编写清晰的程序

  • 在使用inpu()函数时应指定清晰而易于明白的提示。
  • 通过在提示末尾包含一个空格,可将提示与用户输入分开
  • 若提示超过一行,可将提示存储在一个变量当中,再将变量传递给input()函数。
  • 例如:
prompt='If you tell me your name,i will give you a girl friend.'
prompt+="\nSo,what's your name?\n"
name=input(prompt)
print("Your girl friend is fengjie,i konw you are happy,"+name.title()+"!")
#输出为:
#If you tell me your name,i will give you a girl friend.
#So,what's your name?
#输入zhangsan
#Your girl friend is fengjie,i konw you are happy,zhangsan!

(3)使用int()获取数值输入

函数int()可以将数字的字符串转换为数值表示,例如:

prompt='If your age have 18 ,you can read this web.'
prompt+='\nSo,give us your age:\n'
age=int(input(prompt))
if age>=18:
    print("Go ,boy!")
else:
    print("Go out and learning!")
#If your age have 18 ,you can read this web.
#So,give us your age:
#输入21
#Go ,boy!

(4)求模运算符

处理信息时,求模运算符(%)是一个很有用的工具,他将两个数相除并返回余数。

注意:求模运算符不会指出一个数是另一个数的多少倍,而只会指出余数为多少。

number=input("Now,i need you give me a number and i will give you a answer:")
if (int(number)%10)==0:
    print("这个数是10的倍数")
else:
    print("这个数不是10的倍数")
#Now,i need you give me a number and i will give you a answer:
#输出120
#这个数是10的倍数

2、while循环

(1)使用while循环

例如:

#利用while循环数数:
cnt=1
number=int(input("Give me a number:\n"))
while cnt<=number:
    print(str(cnt)+'\t')
    cnt+=1
#Give me a number:
#输入3
#1	
#2	
#3	

(2)让用户选择何时退出循环

prompt="Give me a word,and i will backe to you.\n"
prompt+="When you give me a quit,this progaram will quit.\n"
message=""
while message!="quit":
    message = input(prompt)
    if message !="quit":
        print(message)
#Give me a word,and i will backe to you.
#When you give me a quit,this progaram will quit.
#输入shit
#shit
#Give me a word,and i will backe to you.
#When you give me a quit,this progaram will quit.
#输入quit,终止循环,程序运行结束

(3)使用标志

01、标志定义:再要求很多条件都满足才运行程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志。

02、标志使用:例如,可以让程序标志为True时运行,并在任何事件导致标志的值为False时停止程序的运行。

prompt='Only the light is green,you can walk.'
prompt+='\nGive me the color:\n'
color=""
active=True
while active:
    color=input(prompt)
    if  color==("red"or"yellow"):
        active=False
        print("You should stop")
    else if color=="green":
        print("You can walk,because it's"+color.title())
#Only the light is right,you can walk.
#Give me the color:
#red
#You should stop

(4)break 和 continue

01、break:要立即退出while循环,不在运行循环中余下的代码,也不管条件测试结果如何,可使用break语句。break语句前的代码将被执行,其后的代码将被跳过。

注意:在for循环语句中break也可以使用,效果同while。

02、continue:要返回循环的开头,并根据条件测试的结果决定是否执行循环可使用continue语句。continue语句会跳过其后的代码,并返回到循环的开头

例如:

prompt='Only the lingt is green,you can walk.'
prompt+='\nGive me the color:\n'
color=""
active=True
while active:
    color=input(prompt)
    if color==("red"or"yellow"):
        print("You should stop")
        continue
    elif color=="green":
        print("You can walk,because it's"+color.title())
        break
#Only the lingt is green,you can walk.
#Give me the color:
#red,跳过其后的代码重新返回循环
#You should stop
#Only the lingt is green,you can walk.
#Give me the color:
#输入green则循环将停止

注意:每个while循环都必须要有停止运行的途径,如果程序陷入无限循环,可按住Ctrl+C来结束循环。

3、使用while循环来处理字典和列表

(1)在列表之间移动元素

例如:

u_stu=['zhangsan','lisi','wangmazi']
stu=[]
while u_stu:
    current=u_stu.pop()
    print("Verifying stu:"+current.title())
    stu.append(current)
print('\nThese stus are confirmed:\n')
for confirmeds in stu:
    print(confirmeds)
#Verifying stu:Wangmazi
#Verifying stu:Lisi
#Verifying stu:Zhangsan

#These stus are confirmed:

#wangmazi
#lisi
#zhangsan

(2)删除包含特定值的所有列表元素

利用remove()函数

例如:

pets=['cat','dog','snake','cat','dog']
print(pets)
while "cat"and"dog" in pets:
    pets.remove('cat')
    pets.remove('dog')
print(pets)
#['cat', 'dog', 'snake', 'cat', 'dog']
#['snake']

(3)使用用户输入来填充字典

math={}
active=True
print("I want to know your name and math score.")
while active:
    name=input("\nWhat's your name?\n")
    score=int(input("Give me your score:\n"))
    math[name]=score
    number=60
    if(score<60):
        print("You can't pass this eaxm")
    else:
        print("Pass!")
    repeat=input("Are you the last one?\n")
    if repeat=='Yes':
        active=False
print("\n--Exam Reuslts--")
for name,scores in math.items():
    print(name.title()+",your exam score is:"+str(scores))
#I want to know your name and math score.

#What's your name?
#zhangsan
#Give me your score:
#65
#Pass!
#Are you the last one?
#Yes

#--Exam Reuslts--
#Zhangsan,your exam score is:65

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值