本文是学习齐伟老师的《python全栈工程师》课程的笔记,欢迎学习交流。同时感谢齐老师的精彩传授!
一、课程目标
- 掌握 for 循环语句的结构
- 掌握列表解析的使用方法
- 在程序中应用 for 循环语句
二、详情解读
1.基本形式:
注意:用于for循环的对象必须是可迭代对象!!
判断对象是否是可迭代的:hasattr(obj, ‘iter’)或者 用collections模块
注意:python版本3.8以后,需要用 import collections.abc
2.相关函数:
- range():
用range创建列表时,列表中被使用的值才会占用内存空间,列表中没有被使用的值不会占用内存空间
- zip():
- enumerate():
3.列表解析:
列表解析(list comprehension),又译为”列表推导“
4.其他解析:
5.例题讲解:
例题1:
- 统计如下字符串中每个单词的数量。
– song = “when I am down and oh my soul so weary When troubles come and my heart burdened be Then I am still and wait here in the silence Until you come and sit awhile with me You raise me up so I can stand on mountains YOu raise me up to walk on stormy sears I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains Your raise me up to walk on stormy seas I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mo