一、if语句的使用

  1. 代码示例: ```python cars = [‘audi’, ‘bmw’, ‘subaru’, ‘toyota’]

for car in cars: if car == ‘bmw’: print(car.upper()) #output:BWM else: print(car.title())

  1. :::tips
  2. 注意:if判断中区分大小写,如果大小写无关紧要可以使用.lower()函数转换成小写再判断(临时的,不会改变原变量的值)<br />注意不要忘记冒号!
  3. :::
  4. 2. **and**(**与**):<br />同c/c++中的&&,示例:`if a>b and c>d:`<br />为了增加可读性,也可以:`if (a>b) and (c>d):`
  5. 3. **or**(**或**):<br />同c/c++中的||,示例:`if (a>b) or (c>d):`
  6. 4. 检查**特定值是否在列表中**:**in**
  7. ```python
  8. numbers = [value for value in range(1, 100)]
  9. number = 55
  10. if number in numbers:
  11. print("1")
  12. #output:1
  1. 检查特定值是否包含在列表中:not in (用法与上述类似)

  2. if-else语句:
    if a>b :
    else :

  3. 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) + “.”)

  1. :::tips
  2. Python并不要求if-elif结构后面必须有else代码块。<br />在有些情况下,else代码块很有用;而在其他一些情况下,使用一条elif语句来处理特定的情形更清晰。<br />else是一条包罗万象的语句,只要不满足任何ifelif中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。
  3. :::
  4. 8. 确定列表是不是**空**的:<br />`liebiao=[]`<br />`if liebiao :`<br />当列表内至少有一个元素时返回True;**为空时返回False**。
  5. 9. 使用**多个列表**:
  6. ```python
  7. available_toppings = ['mushrooms', 'olives', 'green peppers',
  8. 'pepperoni', 'pineapple', 'extra cheese']
  9. requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
  10. for requested_topping in requested_toppings:
  11. if requested_topping in available_toppings:
  12. print("Adding " + requested_topping + ".")
  13. else:
  14. print("Sorry, we don't have " + requested_topping + ".")
  15. print("\nFinished making your pizza!")

:::tips output:
Adding mushrooms.
Sorry, we don’t have french fries.
Adding extra cheese.

Finished making your pizza! :::


二、字典

1、基础知识:

  1. 字典是一系列的键-值对(让我想起了c++里的map),与键相关联的值可以是数字、字符串、列表乃至字典。
    在字典中,想存储多少个键值对都可以。
  2. 代码示例
    alien = {'color':'green','points':5}
    print(alien['color']) #输出:green
    print(alien['points']) #输出:5
  3. 添加键值对:
    alien['x_position'] = 0
    alien['y_position'] = 25
  4. 值的修改: ```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:

  1. # This must be a fast alien.
  2. 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’]))

  1. 5. **删除**键值对:<br />`del dictionary_name['key']`
  2. 6. 推荐的风格:
  3. ```python
  4. favorite_languages = {
  5. 'jen': 'python',
  6. 'sarah': 'c',
  7. 'edward': 'ruby',
  8. 'phil': 'python',
  9. }
  10. print("Sarah's favorite_language is " +
  11. favorite_languages['sarah'].title() +
  12. ".")
  13. #Output: Sarah's favorite_language is C.
  1. 遍历所有的键值对:.items()函数
    for key,value in favorite_languages.items():
  2. 遍历所有的
    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!")
  3. 顺序遍历字典中的所有
    for name in sorted(favorite_languages.key()):
  4. 遍历字典中的所有:.value()函数
    for lannguage in favorite_languages.value():
  5. set集合(元素去重):
    for languages in set(favorite_languages.value()):

2、嵌套:

  1. 在列表中嵌套字典: ```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)

  1. :::tips
  2. output:<br />{'color': 'green', 'points': 5}<br />{'color': 'yellow', 'points': 10}<br />{'color': 'red', 'points': 15}
  3. :::
  4. 我们可以来的稍微复杂一点:
  5. ```python
  6. # 创建一个用于存储外星人的空列表
  7. aliens = []
  8. # 创建30个绿色的外星人
  9. for alien_number in range(30): #循环30次
  10. new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
  11. aliens.append(new_alien)
  12. # 对前三个外星人进行一些修改
  13. for alien in aliens[0:3]:
  14. if alien['color'] == 'green':
  15. alien['color'] = 'yellow'
  16. alien['speed'] = 'medium'
  17. alien['points'] = 10
  18. # 我们还可以进一步扩展这个循环,虽然在这里并没有什么用
  19. elif alien['color'] == 'yellow':
  20. alien['color'] = 'red'
  21. alien['speed'] = 'fast'
  22. alien['points'] = 15
  23. # 显示前五个外星人
  24. for alien in aliens[0:5]:
  25. 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’} :::

  1. 在字典中存储列表: ```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)

  1. 3. **在字典中存储字典**:
  2. ```python
  3. users = {
  4. 'aeinstein': {
  5. 'first': 'albert',
  6. 'last': 'einstein',
  7. 'location': 'princeton',
  8. },
  9. 'mcurie': {
  10. 'first': 'marie',
  11. 'last': 'curie',
  12. 'location': 'paris',
  13. }
  14. }
  15. for username, user_info in users.items():
  16. print("\nUsername: "+username)
  17. full_name = user_info['first'] + " " + user_info['last']
  18. location = user_info['location']
  19. print("\tFull name: " + full_name.title())
  20. print("\tLocation: " + location.title())

:::tips output:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton

Username: mcurie
Full name: Marie Curie
Location: Paris :::


3、总结:

  1. 列表嵌套字典的输出格式:
    for pet in pets:
    (indent)for key, value in pet.items():
  2. 字典嵌套列表的输出格式:
    for name, places in favorite_places.items():
    (indent)for place in places:
  3. 字典嵌套字典的输出格式:
    for city, city_info in cities.items:
    (indent)各种变量 = citi_info 子字典中的键(就是赋值)
    (indent)再用这些变量输出即可