《Python编程从入门到实践》——学习python的第八天

python学习的第八天

前言

今天是学习python的第8天,上次学到了遍历字典中的值了,你还记得嘛,不记得了可以去复习一下哦。咱们直接开始

字典

这里分享一个set函数的用法,使得重复的元素只显示一个

favorite_language = {'jen':'Python',
                     'sarah':'c',
                     'edward':'ruby',
                     'phil':'Python'
                     }


print("The following languages have been mentioned:")
for language in set(favorite_language.values()):#这里使用了一个set函数来提取favorite中不同的语言,避免重复,这里是利用set创建一个集合(集合的性质)
    print(language.title())

结果:
The following languages have been mentioned:
C
Ruby
Python

嵌套
有时候需要将字典储存在列表中,或者将列表储存在字典中,这种方式就叫做嵌套。

字典列表

alien_0 = {'color':'green','points':5}
alien_1 = {'color':'yellow','points':10}
alien_2 = {'color':'red','points':15}


aliens= [alien_0,alien_1,alien_2]#这里不需要加上单引号或者双引号,因为加上之后会把这些当成字符串,输出的只是字典的名称
for alien in aliens:
    print(alien)

结果:
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘red’, ‘points’: 15}

这里是定义字典,再嵌入列表中。

嵌入任意数量的字典

#创建一个空白列表用于储存外星人
aliens = []
#创建30个绿色的外星人
for alien_number in range(30):#核心操作,控制了数量
    new_alien = {'color':'green','points':5}
    aliens.append(new_alien)#每进行了一次,就进行扩充


#显示前5个外星人。
for alien in aliens[:5]:#这里使用了切片,可以完整的从开始到末尾开始
    print(alien)
print("...")
print(f"Total number of aliens:{len(aliens)}")#这里用来Len函数对其进行了计算

结果:
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5}

Total number of aliens:30

对列表中的字典进行修改

#创建一个空白列表用于储存外星人
aliens = []
#创建30个绿色的外星人
for alien_number in range(30):#核心操作,控制了数量
    new_alien = {'color':'green','points':5}
    aliens.append(new_alien)#每进行了一次,就进行扩充
#修改前三个外星人的信息
for alien in aliens[:3]:
    if alien['color'] =='green':
        alien['color'] ='yellow'
        alien['points'] = 10 #别忘了这里是列表中嵌套字典 alien是新的变量能够代替字典 new_alien


for alien in aliens[0:5]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['points'] = 10
    elif alien['color'] == 'yellow':
        alien['color'] = 'red'
        alien['points'] = 15
#显示前5个外星人。
for alien in aliens[:5]:#这里使用了切片,可以完整的从开始到末尾开始
    print(alien)
print("...")
print(f"Total number of aliens:{len(aliens)}")#这里用来Len函数对其进行了计算

结果:
{‘color’: ‘red’, ‘points’: 15}
{‘color’: ‘red’, ‘points’: 15}
{‘color’: ‘red’, ‘points’: 15}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘yellow’, ‘points’: 10}

Total number of aliens:30

使用新字典来代替原来的字典

在字典中储存列表
就拿pizza做例子吧。pizza有很多口味,而且有许多配方,而配方中又不止一直材料这个时候就需要使用列表来存储了。

#存储所点pizza的信息
pizza = {'crust':'thick',
         'toppings':['mushroom','extra cheese']#直接在字典信息中输入一个列表即可
}
#概述所点的比萨。
print(f"You ordered a {pizza['crust']}-crust pizza"
      f" with the following toppings:")#如果print的语句太长可以换行,但是每一行需要的语句需要一个双引号
for topping in pizza['toppings']:
    print("\t"+topping)#这里如果不使用“+”号程序会呈现错误,运行不出来。

结果:
You ordered a thick-crust pizza with the following toppings:
mushroom
extra cheese

注意代码中的注释哦

实战

favorite_languages = {
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
}#上述操作建立一个含列表的字典


for name,languages in favorite_languages.items():#这里是遍历了一下键值对,所以需要使用到items()方法,
    print(f"\n{name.title()}'s favorite languages are:")#这里是打印出键
   for language in languages:#这里是对值进行打印,但是因为是一个列表所以需要来遍历
        print(f"\t{language.title()}")

结果:
Jen’s favorite languages are:
Python
Ruby

Sarah’s favorite languages are:
C

Edward’s favorite languages are:
Ruby
Go

Phil’s favorite languages are:
Python
Haskell

在字典中存储字典
好比如每个人都有自己的名字,同时他们也有很多自己的账户用户名,这个时候我们需要使用这个了字典中嵌套字典了

users = {
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton',
    },#这里是字典包含字典


    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris'
    },
}
for username,user_infor in users.items():#这里是遍历整个字典。username代表的是名字,user_infor代表的是字典
    print(f"\nUsername:{username}")#打印名字
    full_name = f"{user_infor['first']}{user_infor['last']}"#建立了一个新变量 = 花括号内的变量都是字典中的内容
    location = user_infor['location']
    print(f"\tFull name:{full_name.title()}")
    print(f"\tLocation:{location}")

结果:
Username:aeinstein
Full name:Alberteinstein
Location:princeton

Username:mcurie
Full name:Mariecurie
Location:paris

用户输入

函数input的工作原理
函数input()会让程序暂停运行,等待用户输入一些文本。获取用户输入后,python将其赋给一个变量,以方便你的使用

message = input("Tell me something,and I will repeat it back to "
                "you:")#这里是相当于c语言中的scanf但是会更加的方便,可以看到提示信息后再输入
print(message)

结果:
Tell me something,and I will repeat it back to you:yinyanghaixing#我所输入的
yinyanghaixing

如果我们所需要的提示太多了,我们可以多使用一个变量来代替

prompt = "If you tell us who you are,we can personalize the massage you see."
prompt +="\n What's your name"


name = input(prompt)
print(name)

结果:
If you tell us who you are,we can personalize the massage you see.
What’s your nameyinyang
yinyang

使用int()来获得数值输入

>>> age = input('How old are you?')
How old are you?21
>>> age
'21'#这里是python直接将其定义为了字符串类型
>>> age > 18#将其与数值进行计较时,程序会出现错误,因为一个时 ‘str’类型一个是‘int’类不能进行比较
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    age > 18
TypeError: '>' not supported between instances of 'str' and 'int'
>>> age = int(age)#使用int函数将age转换为int类型
>>> age > 18
True#从而可以进行比较

这一次都是大片的代码,所以要认真的分析看下,如有错误欢迎评论区指出,谢谢。

  • 11
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值