栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

2022年5月18日学习笔记

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2022年5月18日学习笔记

Python学习笔记

第五章 if语句 + 第六章 字典
  • 一、条件测试
  • 二、if语句
  • 三、使用if语句处理列表
  • 四、使用字典
  • 五、遍历字典
  • 六、嵌套


一、条件测试

每条if语句的核心都是一个值为True或False的表达式。

如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果为False,Python就忽略这些代码。

方法描述
==判断是否相等
!=判断是否不等
<=小于等于
>=大于等于
and检查两个条件是否都满足
or检查两个条件是否至少有一个满足
in检查特定值是否包含在列表中
not in检查特定值是否不包含在列表中
布尔表达式记录条件
>>> 1 == 1
True
>>> 1 != 1
False
>>> 1 <= 1
True
>>> 1 >= 2
False
>>> 1 >= 0 and 2 >= 1
True
>>> cars = ['bmw','audi','toyota','byd']
>>> ('bmw' in cars) or ('subaru' in cars)
#使用括号更为简洁
True
>>> 'subaru' not in cars
True
二、if语句
  • 在if语句中,缩进的作用与for循环中相同。如果测试通过了,将执行if语句后面所有所进的代码行,否则将忽略他们。

  • else包罗万象,若要知道最重要测试的条件,应考虑使用一个elif代码块来代替else代码块。

  • 若想执行一个代码块,就使用 if-elif-else 结构;如果要运行多个代码块,就使用一系列独立的 if 语句。

age = 19
if age < 2:
    print('你是一个婴儿!')
elif age < 4:
    print('你正蹒跚学步!')
elif age < 13:
    print('你是儿童!')
elif age < 20:
    print('你是青少年!')
elif age < 65:
    print('你是成年人!')
else:
    print('你是老年人!')

favorite_fruits = ['banlala','watermelon','strawberry']
if 'apple' in favorite_fruits :
    print('You really like apples!')
if 'banlala' in favorite_fruits :
    print('You really like banlalas!')
    
输出结果为:
你是青少年!
You really like banlalas!
三、使用if语句处理列表

1、检查特殊元素

request_toppings = ['mushrooms','green peppers','extra cheese']
for request_topping in request_toppings:
    if request_topping == 'green peppers':
        print('Sorry! The green peppers is out now!')
    else:
        print('Adding' + request_topping +'.')
print('nFinished making your pizza!')

输出结果为:
Addingmushrooms.
Sorry! The green peppers is out now!
Addingextra cheese.

Finished making your pizza!

2、确定列表不是空的
Python将在列表至少包含一个元素时返回True,在列表为空时返回False。

request_toppings = []
if request_toppings: #显然此处等价于if False: 
    for request_topping in request_toppings:
        print('Adding' + request_topping + '.')
else:
    print('Are you sure to buy a plain pizza?')
    
输出结果为:
Are you sure to buy a plain pizza?

3、使用多个列表

requested_toppings = ['mushrooms','french fries','extra cheese']
avalible_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
for requested_topping in requested_toppings:
    if requested_topping in avalible_toppings:
        print('Adding' + requested_topping + '.')
    else:
        print("Sorry, we dont't have " + requested_topping + '.')

输出结果为:
Addingmushrooms.
Sorry, we dont't have french fries.
Addingextra cheese.
四、使用字典
  • 字典是一系列键-值对。每个键都与一个值相关联,可以使用键来访问与之相关联的值。
  • 键和值之间用冒号分隔,键-值对之间用逗号分隔。

1、访问字典中的值

>>> alien_0 ={'color':'green','points':5}
>>> new_points = alien_0['points']
>>> print("You just earned " + str(new_points) + "points!")
You just earned 5points!
>>> print("You just earned " + str(new_points) + " points!")
You just earned 5 points!
>>> alien_0["color"] #不区分单双引号
'green'
>>> alien_0[0] #不可使用索引
Traceback (most recent call last):
  File "", line 1, in 
    alien_0[0]
KeyError: 0

2、添加键-值对、创建空字典
要添加键-值对,可依次指定字典名、用方括号括起的键和相关联的值。

>>> alien_0 = {} #直接创建一个空字典
>>> alien_0['x_position'] = 0
>>> alien_0['y_position'] = 25
>>> print(alien_0)
{'x_position': 0, 'y_position': 25}

3、修改字典中的值
要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值。类比列表修改元素。

alien_0 = {'x_position' : 0,'y_position' : 25,'speed': 'medium'}
print('Original x_position: ' + str(alien_0['x_position']))
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else: #一定很快
    x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print('New x_position: ' + str(alien_0['x_position']))

输出结果为:
Original x_position: 0
New x_position: 2

4、删除键-值对

  • 使用del 来永久删除字典的键-值对
  • 使用del 语句时,必须指定字典名和要删除的键。
alien_0 ={'color':'green','points':5}
print(alien_0)
del alien_0['color']
print(alien_0)

输出结果为:
{'color': 'green', 'points': 5}
{'points': 5}

5、由类似对象组成的字典

确定需要使用多行来定义字典时,在输入左花括号后按回车键,再在下一行缩进四个空格,指定第一个键-值对,并在其后加上一个逗号。

favorite_language = {
    'jen':'python',
    'sarah':'C',
    'edward':'ruby',
    'phil':'python',
    }
print("Sarah's favorite language is " +
      favorite_language['sarah'] + '.')
#回车以保持美观
输出结果为:
Sarah's favorite language is C.
五、遍历字典

1、遍历所有的键-值对
方法:.items()
遍历字典时,键-值对的返回顺序与存储顺序未必保持一致。
示例1:

user_0 = {
    'username':'efermi',
    'first':'enrico',
    'last':'fermi',
    }
for key, value in user_0.items():
    print('nkey: ' + key)
    print('value: ' + value)

输出结果为:

key: username
value: efermi

key: first
value: enrico

key: last
value: fermi

示例2:

favorite_languages = {
    'jen':'python',
    'sarah':'C',
    'edward':'ruby',
    'phil':'python',
    }
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is"
                         " " + language + ".")
                         
输出结果为:
Jen's favorite language is python.
Sarah's favorite language is C.
Edward's favorite language is ruby.
Phil's favorite language is python.

2、遍历字典中的所有键
方法:.keys()或者直接使用字典名称
for name in favorite_languages.keys():
等价于
for name in favorite_languages:

favorite_languages = {
    'jen':'python',
    'sarah':'C',
    'edward':'ruby',
    'phil':'python',
    }
friends = ['phil','sarah']
for name in favorite_languages.keys():
    print(name.title())
    if name in friends:
        print("Hi " + name.title() +
              ", I see your favorite language is " +
               favorite_languages[name].title() + "!n")
if 'erin' not in favorite_languages:
    print('Erin, please take our poll!')

输出结果为:
Jen
Sarah
Hi Sarah, I see your favorite language is C!

Edward
Phil
Hi Phil, I see your favorite language is Python!

Erin, please take our poll!

3、按顺序遍历字典中的所有键
方法:sorted()函数按字母排序

favorite_languages = {
    'jen':'python',
    'sarah':'C',
    'edward':'ruby',
    'phil':'python',
    }
for name in sorted(favorite_languages.keys()):
    print(name.title() + ", thank you for takeing the poll.")
    
输出结果为:
Edward, thank you for takeing the poll.
Jen, thank you for takeing the poll.
Phil, thank you for takeing the poll.
Sarah, thank you for takeing the poll.

4、遍历字典中的所有值
方法:.values()

  • 通过对包含重复元素的列表调用 set() 函数,可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。
favorite_languages = {
    'jen':'python',
    'sarah':'C',
    'edward':'ruby',
    'phil':'python',
    }
for value in set(favorite_languages.values()):
    print(value.title())

输出结果为:
C
Ruby
Python #重复的值被省去了

5、按顺序遍历字典中的所有值
同按顺序遍历字典中的所有键一样,使用sorted()函数即可

favorite_languages = {
    'jen':'python',
    'sarah':'C',
    'edward':'ruby',
    'phil':'python',
    }
for value in sorted(set(favorite_languages.values())):
    print(value.title())

输出结果为:
C
Python
Ruby
六、嵌套

1、字典列表
将一些列字典储存在列表中

#创建一个空的机器人列表
aliens = []
#生成30个机器人并存储于列表中
for alien in range(30):
    new_alien = {'color':'green','points':5,'speed':'slow'}
    aliens.append(new_alien)
for alien in aliens[0:3]:
    if alien["color"] == 'green':
        alien["color"] = 'yellow'
        alien["points"] = 10
        alien["speed"] = 'medium'
for alien in aliens[0:5]:
    print(alien)
print("...")
print('Total number of aliens: ' + str(len(aliens)))

输出结果为:
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30

2、在字典中存储列表

favorite_laguages = {
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
}
for name, languages in favorite_laguages.items():
    if len(languages) == 1:
        print("n" + name.title() + "'s favorite language is " + languages[0].title())
    else:
        print("n" + name.title() + "'s favorite language are: ")
        for language in languages:
            print(language.title())

输出结果为:

Jen's favorite language are: 
Python
Ruby

Sarah's favorite language is C

Edward's favorite language are: 
Ruby
Go

Phil's favorite language are: 
Python
Haskell

3、在字典中储存字典

users = {
    'aeinstein':{
        'first_name':'albert',
        'last_name':'einstein',
        'location':'princeton',
    },
    'mcurie':{
        'first_name':'marie',
        'last_name':'cruie',
        'location':'paris',
    },
}
for name, info in users.items():
    print("nUsername: " + name.title())
    print("tFull name: " + (info['first_name']).title()+ " " + (info['last_name']).title())

输出结果为:
Username: Aeinstein
	Full name: Albert Einstein

Username: Mcurie
	Full name: Marie Cruie

注:

  • 表示每位用户的字典的结构都相同,虽然Python并没有这样的要求,但这使得嵌套的字典处理起来更加容易。
  • 倘若每位用户的字典都包含不同的键,for循环内部的代码将更复杂。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/915894.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号