Python3:基本语法之三(判断、字典)

检查是否相等时不考虑大小写

在Python中检查是否相等时区分大小写,例如,两个大小写不同的值会被视为不相等:

>>> car = 'Audi'
>>> car == 'audi'
False
>>> car = 'Audi'
>>> car.lower() == 'audi'
True

函数 lower()不会修改存储在变量 car 中的值,因此进行这样的比较时不会影响原来的变量:

检查是否不相等

要判断两个值是否不等,可结合使用惊叹号和等号"!=" ,其中的惊叹号表示不,在很多编程语言中都如此。

requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
	print("Hold the anchovies!")

输出结果:

Hold the anchovies!

比较数字

条件语句中可包含各种数学比较,如小于、小于等于、大于、大于等于:

>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False

检查多个条件

要检查是否两个条件都为 True ,可使用关键字 and 将两个条件测试合二为一。

>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
False
>>> age_1 = 22
>>> age_0 >= 21 and age_1 >= 21
True

使用or检查多个条件

关键字 or 也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试

>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 or age_1 >= 21
True
>>> age_0 = 18
>>> age_0 >= 21 or age_1 >= 21
False

检查特定值是否包含在列表中

要判断特定的值是否已包含在列表中,可使用关键字 in 。

>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
>>> 'pepperoni' in requested_toppings
False

检查特定值是否不包含在列表中

确定特定的值未包含在列表中很重要;在这种情况下,可使用关键字 not in 。

banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
	print(user.title() + ", you can post a response if you wish.")

输出结果:

Marie, you can post a response if you wish.

布尔表达式

与条件表达式一样,布尔表达式的结果要么为 True ,要么为 False 。

game_active = True
can_edit = False

简单的if语句

最简单的if语句只有一个测试和一个操作:

if conditional_test :
	do something

if-else语句

age = 17
if age >= 18:
	print("You are old enough to vote!")
	print("Have you registered to vote yet?")
else:
	print("Sorry, you are too young to vote.")
	print("Please register to vote as soon as you turn 18!")

if-elif-else 结构

Python并不要求 if-elif 结构后面必须有 else 代码块。

age = 12
if age < 4:
	print("Your admission cost is $0.")
elif age < 18:
	print("Your admission cost is $5.")
else:
	print("Your admission cost is $10.")

字典

alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])

输出结果:

green
5

添加键-值对

字典是一种动态结构,可随时在其中添加键 — 值对。

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

输出结果:

{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

Python不关心键 — 值对的添加顺序,而只关心键和值之间的关联关系。

修改字典中的值

alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")

alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")

输出结果:

The alien is green.
The alien is now yellow.

删除键 - 值对

对于字典中不再需要的信息,可使用 del 语句将相应的键 — 值对彻底删除。使用 del 语句时,必须指定字典名和要删除的键。

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

del alien_0['points']
print(alien_0)

让Python将键 ‘points’ 从字典 alien_0 中删除,同时删除与这个键相关联的值。输出表明,键 ‘points’ 及其值 5 已从字典中删除,但其他键 - 值对未受影响:

{'color': 'green', 'points': 5}
{'color': 'green'}

由类似对象组成的字典

favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}

确定需要使用多行来定义字典时,在输入左花括号后按回车键,再在下一行缩进四个空格,指定第一个键 — 值对,并在它后面加上一个逗号。此后你再次按回车键时,文本编辑器将自动缩进后续键 — 值对,且缩进量与第一个键 - 值对相同。

遍历字典

user_0 = {
	'username': 'efermi',
	'first': 'enrico',
	'last': 'fermi',
	}

for key, value in user_0.items():
	print("\nKey: " + key)
	print("Value: " + value)

输出结果:

Key: last
Value: fermi

Key: first
Value: enrico

Key: username
Value: efermi

注意,即便遍历字典时,键 — 值对的返回顺序也与存储顺序不同。Python不关心键 — 值对的存储顺序,而只跟踪键和值之间的关联关系。

遍历字典中的所有键

在不需要使用字典中的值时,方法 keys() 很有用。

favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}
for name in favorite_languages.keys():
	print(name.title())

输出结果:

Jen
Sarah
Phil
Edward

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

获取字典的元素时,获取顺序是不可预测的。要以特定的顺序返回元素,一种办法是在 for 循环中对返回的键进行排序。为此,可使用函数 sorted() 来获得按特定顺序排列的键列表的副本:

favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}
	
for name in sorted(favorite_languages.keys()):
	print(name.title() + ", thank you for taking the poll.")

输出结果:

Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.

遍历字典中的所有值

favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}

print("The following languages have been mentioned:")
for language in favorite_languages.values():
	print(language.title())

输出结果:

The following languages have been mentioned:
Python
C
Python
Ruby

集合

为剔除重复项,可使用集合(set)。集合类似于列表,但每个元素都必须是独一无二的。

favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}
	
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
	print(language.title())

输出结果:

The following languages have been mentioned:
Python
C
Ruby

字典列表

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}

在字典中存储列表

pizza = {
	'crust': 'thick',
	'toppings': ['mushrooms', 'extra cheese'],
	}

print("You ordered a " + pizza['crust'] + "-crust pizza " + 
	  "with the following toppings:")

for topping in pizza['toppings']:
	print("\t" + topping)

输出结果:

You ordered a thick-crust pizza with the following toppings:
	mushrooms
	extra cheese

在字典中存储字典

users = {
	'aeinstein': {
		'first': 'albert',
		'last': 'einstein',
		'location': 'princeton',
		},
		
	'mcurie': {
		'first': 'marie',
		'last': 'curie',
		'location': 'paris',
		},
	}

for username, user_info in users.items():
	print("\nUsername: " + username)
	full_name = user_info['first'] + " " + user_info['last']
	location = user_info['location']
	
	print("\tFull name: " + full_name.title())
	print("\tLocation: " + location.title())

输出结果:

Username: aeinstein
	Full name: Albert Einstein
	Location: Princeton

Username: mcurie
	Full name: Marie Curie
	Location: Paris

这里每个字典的结构都相同,虽然Python并没有这样的要求,但这使得嵌套的字典处理起来更容易。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

R-QWERT

你的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值