一、if语句的使用
- 代码示例: ```python cars = [‘audi’, ‘bmw’, ‘subaru’, ‘toyota’]
for car in cars: if car == ‘bmw’: print(car.upper()) #output:BWM else: print(car.title())
:::tips注意:if判断中区分大小写,如果大小写无关紧要可以使用.lower()函数转换成小写再判断(临时的,不会改变原变量的值)<br />注意不要忘记冒号!:::2. **and**(**与**):<br />同c/c++中的&&,示例:`if a>b and c>d:`<br />为了增加可读性,也可以:`if (a>b) and (c>d):`3. **or**(**或**):<br />同c/c++中的||,示例:`if (a>b) or (c>d):`4. 检查**特定值是否在列表中**:**in**```pythonnumbers = [value for value in range(1, 100)]number = 55if number in numbers:print("1")#output:1
检查特定值是否不包含在列表中:not in (用法与上述类似)
if-else语句:
if a>b :else :if-elif-else语句(同c/c++中的else if): ```python age = 12
if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 elif age >= 65: price = 5
print(“Your admission cost is $” + str(price) + “.”)
:::tipsPython并不要求if-elif结构后面必须有else代码块。<br />在有些情况下,else代码块很有用;而在其他一些情况下,使用一条elif语句来处理特定的情形更清晰。<br />else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。:::8. 确定列表是不是**空**的:<br />`liebiao=[]`<br />`if liebiao :`<br />当列表内至少有一个元素时返回True;**为空时返回False**。9. 使用**多个列表**:```pythonavailable_toppings = ['mushrooms', 'olives', 'green peppers','pepperoni', 'pineapple', 'extra cheese']requested_toppings = ['mushrooms', 'french fries', 'extra cheese']for requested_topping in requested_toppings:if requested_topping in available_toppings:print("Adding " + requested_topping + ".")else:print("Sorry, we don't have " + requested_topping + ".")print("\nFinished making your pizza!")
:::tips
output:
Adding mushrooms.
Sorry, we don’t have french fries.
Adding extra cheese.
Finished making your pizza! :::
二、字典
1、基础知识:
- 字典是一系列的键-值对(让我想起了c++里的map),与键相关联的值可以是数字、字符串、列表乃至字典。
在字典中,想存储多少个键值对都可以。 - 代码示例:
alien = {'color':'green','points':5}print(alien['color']) #输出:greenprint(alien['points']) #输出:5 - 添加键值对:
alien['x_position'] = 0alien['y_position'] = 25 - 值的修改: ```python alien_0 = {‘x_position’: 0, ‘y_position’: 25, ‘speed’: ‘medium’} print(“Original position: “ + str(alien_0[‘x_position’]))
Move the alien to the right.
Figure out how far to move the alien based on its speed.
if alien_0[‘speed’] == ‘slow’: x_increment = 1 elif alien_0[‘speed’] == ‘medium’: x_increment = 2 else:
# This must be a fast alien.x_increment = 3
The new position is the old position plus the increment.
alien_0[‘x_position’] = alien_0[‘x_position’] + x_increment #修改
print(“New position: “ + str(alien_0[‘x_position’]))
5. **删除**键值对:<br />`del dictionary_name['key']`6. 推荐的风格:```pythonfavorite_languages = {'jen': 'python','sarah': 'c','edward': 'ruby','phil': 'python',}print("Sarah's favorite_language is " +favorite_languages['sarah'].title() +".")#Output: Sarah's favorite_language is C.
- 遍历所有的键值对:.items()函数
for key,value in favorite_languages.items(): - 遍历所有的键:
for name in favorite_languages.keys():
or:for name in favorite_languages:“.keys()”可以省略,因为默认是指的键;
还可以用词来查找一个键是否存在于字典中:if 'erin' not in favorite_languages.keys():
(indentation)print("Erin, please take our poll!") - 按顺序遍历字典中的所有键:
for name in sorted(favorite_languages.key()): - 遍历字典中的所有值:.value()函数
for lannguage in favorite_languages.value(): - set集合(元素去重):
for languages in set(favorite_languages.value()):
2、嵌套:
- 在列表中嵌套字典: ```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)
:::tipsoutput:<br />{'color': 'green', 'points': 5}<br />{'color': 'yellow', 'points': 10}<br />{'color': 'red', 'points': 15}:::我们可以来的稍微复杂一点:```python# 创建一个用于存储外星人的空列表aliens = []# 创建30个绿色的外星人for alien_number in range(30): #循环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['speed'] = 'medium'alien['points'] = 10# 我们还可以进一步扩展这个循环,虽然在这里并没有什么用elif alien['color'] == 'yellow':alien['color'] = 'red'alien['speed'] = 'fast'alien['points'] = 15# 显示前五个外星人for alien in aliens[0:5]:print(alien)
:::tips
output:
{‘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’}
:::
- 在字典中存储列表:
```python
存储所点比萨的信息
pizza = { ‘crust’: ‘thick’, ‘toppings’: [‘mushrooms’, ‘extra cheese’], #这里使用了列表 } #哇toppings是“浇头”的意思,我一直以为“浇头”是方言
概述所点的比萨
print(“You ordered a “ + pizza[‘crust’] + “-crust pizza “ + “with the following toppings:”)
for topping in pizza[‘toppings’]: print(“\t” + topping)
3. **在字典中存储字典**:```pythonusers = {'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())
:::tips
output:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
:::
3、总结:
- 列表嵌套字典的输出格式:
for pet in pets:
(indent)for key, value in pet.items(): - 字典嵌套列表的输出格式:
for name, places in favorite_places.items():
(indent)for place in places: - 字典嵌套字典的输出格式:
for city, city_info in cities.items:
(indent)各种变量 = citi_info 子字典中的键(就是赋值)
(indent)再用这些变量输出即可
