For 循环

For循环是迭代对象元素的常用方法(在第一个示例中,列表)

具有可迭代方法的任何对象都可以在for循环中使用。

python的一个独特功能是代码块不被{} 或begin,end包围。相反,python使用缩进,块内的行必须通过制表符缩进,或相对于周围的命令缩进4个空格。

虽然这一开始可能看起来不直观,但它鼓励编写更易读的代码,随着时间的推移,你会学会喜欢它

In [1]

#取第一个列表成员(可迭代),暂称它数字(打印它)
#取列表的第二个成员(可迭代),暂时将其称为数字,等等......for number in [23, 41, 12, 16, 7]: print(number)
print('Hi')
23
41
12
16
7
Hi

枚举

返回一个元组,其中包含每次迭代的计数(从默认为0开始)和迭代序列获得的值:

In [2]

friends = ['steve', 'rachel', 'michael', 'adam', 'monica']
for index, friend in enumerate(friends):print(index,friend)
0 steve
1 rachel
2 michael
3 adam
4 monica

Task

从文本中删除标点符号并将最终产品转换为列表:

On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, "This could be Heaven or this could be Hell" Then she lit up a candle and she showed me the way

(加州旅馆)

In [3]

text = '''On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, "This could be Heaven or this could be Hell" Then she lit up a candle and she showed me the way'''

In [4]

print(text)
On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, "This could be Heaven or this could be Hell" Then she lit up a candle and she showed me the way

基本上,任何具有可迭代方法的对象都可以在for循环中使用。即使是字符串,尽管没有可迭代的方法 - 但我们不会在这里继续。具有可迭代方法基本上意味着数据可以以列表形式呈现,其中有序地存在多个值。

In [5]

for char in '-.,;\n"\'':text = text.replace(char,' ')
print(text)
On a dark desert highway  cool wind in my hair Warm smell of colitas  rising up through the air Up ahead in the distance  I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway  I heard the mission bell And I was thinking to myself   This could be Heaven or this could be Hell  Then she lit up a candle and she showed me the way

In [6]

# Split converts string to list.
# Each item in list is split on spaces
text.split(' ')[0:20]
['On','a','dark','desert','highway','','cool','wind','in','my','hair','Warm','smell','of','colitas','','rising','up','through','the']

In [7]

# Dont want to have non words in my list for example ''
# which in this case are things of zero length
len('')
0

In [8]

# Making new list with no empty words in it
cleaned_list = []

In [9]

for word in text.split(' '): word_length = len(word)if word_length > 0:cleaned_list.append(word)

In [10]

cleaned_list[0:20]
['On','a','dark','desert','highway','cool','wind','in','my','hair','Warm','smell','of','colitas','rising','up','through','the','air','Up']

Continue

continue语句将转到循环的下一次迭代

continue语句用于忽略某些值,但不会中断循环

In [11]

cleaned_list = []for word in text.split(' '): if word == '':continuecleaned_list.append(word)
cleaned_list[1:20]
['a','dark','desert','highway','cool','wind','in','my','hair','Warm','smell','of','colitas','rising','up','through','the','air','Up']

Break

break语句将完全打断循环

In [12]

cleaned_list = []

In [13]

for word in text.split(' '): if word == 'desert':print('I found the word I was looking for')breakcleaned_list.append(word)
cleaned_list
I found the word I was looking for
['On', 'a', 'dark']

Task (顺道介绍一下Range函数)

  1. 编写一个Python程序,它迭代整数从1到50(使用for循环)。对于偶数的整数,将其附加到列表even_numbers。对于奇数的整数,将其附加到奇数奇数列表中

In [14]

# Making empty lists to append even and odd numbers to.
even_numbers = []
odd_numbers = []for number in range(1,51):if number % 2 == 0:even_numbers.append(number)else: odd_numbers.append(number)    

In [15]

print("Even Numbers: ", even_numbers)
Even Numbers:  [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]

In [16]

print("Odd Numbers: ", odd_numbers)
Odd Numbers:  [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]

Python 2 vs Python 3 (Range函数的不同点)

python 2 xrange and python 3 range are same (resembles a generator) python 2 range生成一个list

注意: 较长的列表会很慢

Python基础课程-for循环相关推荐

  1. Python 基础课程第五天

    Python 基础课程第五天 第四章:控制语句 循环结构 for循环和可迭代对象遍历 可迭代对象 range 对象 嵌套循环和综合练习 break 语句 continue 语句 else 语句 循环代 ...

  2. python 基础课程第三天

    文章目录 python 基础课程第三天 字符串 可变字符串 基本运算符 复合赋值运算符 运算符优先级 序列 列表简介 列表的创建 基本语法[]创建 list()创建 range()创建整数列表 推导式 ...

  3. Python 基础课程第十天

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 Python 基础课程第十天 第八章文件操作(IO 技术) 文本文件和二进制文件 文件操作相关模块概述 创建文件对象open() 文本 ...

  4. python教程循环语句,Python基础教程之循环语句(for、while和嵌套循环)

    循环可以用来重复执行某条语句,直到某个条件得到满足或遍历所有元素. 1 for循环 是for循环,可以把集合数据类型list.tuple.dict.set的元素遍历出来. (1)对list进行循环 c ...

  5. python while循环if_详解python基础之while循环及if判断

    wlile循环 while True表示永远为真,不管是什么条件都会向下执行,下面是写的一个例子. #!/usr/bin/env python age = 24 #给age赋一个值 while Tru ...

  6. 20190508——python基础(if...in...循环语句、while循环、两种循环对比)

    二.python基础(if...in...循环语句.while循环.两种循环对比) 1.for...in...循环语句 1)for循环:空房间 # 空房间的学名叫[元素](item),因为英文是ite ...

  7. Python 基础课程第十一天

    Python 基础课程第十一天 第七章模块(module) 1. 模块化(module)程序设计理念 1.1 模块和包概念的进化史 1.2 标准库模块(standard library) 1.3 为什 ...

  8. Python 基础课程第八天

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 Python 基础课程第八天 第6 章(1) 面向对象初步 方法没有重载 方法的动态性 私有属性和私有方法(实现封装) @proper ...

  9. python 基础课程第二天

    文章目录 python 基础课程第二天 链式赋值 系列解包赋值 常量 最基本内置数据类型介绍 数字和基本运算符 整数 使用INT()实现类型转换: 自动转型: 整数可以多大 浮点数 类型转换和四舍五入 ...

最新文章

  1. javascript功能_功能性JavaScript简介
  2. ASP.NET MVC Display Mode 移动端视图 配置对微信内置浏览器的识别
  3. redis 入门教程
  4. Windows进程与线程学习笔记(六)—— 线程切换
  5. NeurIPS'20 | 通过文本压缩,让BERT支持长文本
  6. mysql历史数据备份_Mysql存储过程历史表备份
  7. Spring AOP源码分析(二)JDK动态代理和CGLIB介绍
  8. python计算思维的概念_用Python学计算思维turtle详解
  9. hadoop hdfs空间满后重新启动不了
  10. centos/linux下的安装Nginx
  11. 数学建模写作指导20篇(一)-如何写好数学建模论文?
  12. 对称加密与非对称加密算法
  13. Python爬虫入门【11】:半次元COS图爬取
  14. python识别验证码 免费API接口
  15. 做你喜欢做的事,财富会随之而来
  16. 【100%通过率】华为OD机试真题 Python 实现【微服务的集成测试】【2023 Q1 | 100分】
  17. Code First开发系列之管理并发和事务
  18. UKF-协方差矩阵分解
  19. 使用c语言实现复数运算的程序,用C语言实现的复数运算程序设计
  20. hander机制原理

热门文章

  1. 百度 凤巢 机器学习实习生面经
  2. (PHP)图片加文字和图片合成
  3. 云端软件平台“天涯海阁”定制版 /
  4. TPFanControl.ini
  5. kaiser密码的加密与解密
  6. 频繁收到小米发送的AC开头的短信的解决方案
  7. 数据分析师+前途无忧爬虫分析
  8. 读《史蒂芬·乔布斯传》有感
  9. Django中间件Middleware
  10. (iptables)火墙策略读取的先后顺序 + 引入数据包状态