x = 1
while x <= 100:
    print(x)
    x += 1
 
基本上, 可迭代对象是可使用for循环进行遍历的对象。
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
    print(number)
 
鉴于迭代特定范围内的数是一种常见的任务:
>>> range(0, 10)
range(0, 10)
>>> list(range(0, 10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
下面的程序打印数1~100:
for number in range(1,101):
print(number)
 
迭代字典
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
    print(key, 'corresponds to', d[key])
可在for循环中使用序列解包
for key, value in d.items():
    print(key, 'corresponds to', value)
 
一些迭代工具
1.并行迭代
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
for i in range(len(names)):
print(names[i], 'is', ages[i], 'years old')
函数zip:
>>> list(zip(names, ages))
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
for name, age in zip(names, ages):
print(name, 'is', age, 'years old')
函数zip可缝合任一序列,但在最短序列用完后停止缝合
>>> list(zip(range(5), range(100000000)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
 
2.迭代时获取索引
如果想替换一个字符串列表中所有包含子串'xxx'的字符串,有很多种方法
一种是这样:
index = 0
for string in strings:
    if 'xxx' in string:
        strings[index] = '[censored]'
    index += 1
但使用内置函数enumerate更好:
for index, string in enumerate(strings):
    if 'xxx' in string:
        strings[index] = '[censored]'
 
3.反向迭代和排序后再迭代
>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello, world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'
sorted返回一个列表,而reversed像zip那样返回一个更神秘的可迭代对象。你无需关心这到底意味着什么,只管在for循环或join等方法中使用它,不会有任何问题。只是你不能对它执行索引或切片操作,也不能直接对它调用列表的方法。要执行这些操作,可先使用list对返回的对象进行转换。
要按字母表排序,可先转换为小写。为此,可将sort或sorted的key参数设置为str.lower。例如, sorted("aBc", key=str.lower)返回['a', 'B', 'c']。
 
break跳出循环
continue结束当前迭代并跳到下一次迭代开头
一般这样会让代码简洁很多:
while True:
    if(): break
 
这里在循环中添加一条else子句,它在没有调用break时才执行。(即在循环正常结束时采取某种措施)
for n in m : 
    if :
        break
else:
无论是for还是while循环都可使用continue,break和else子句
 
 

Python-11-循环的更多相关文章

  1. python for循环 - python基础入门(11)

    在python开发中,除了前篇文章介绍的while循环还有一个for循环也经常使用,两者使用都是大同小异,for循环的使用相对于while循环更加灵活,下面我们一起来了解下具体区别. 一.for 循环 ...

  2. python基础-循环

    循环 循环 要计算1+2+3,我们可以直接写表达式: >>> 1 + 2 + 3 6 要计算1+2+3+...+10,勉强也能写出来. 但是,要计算1+2+3+...+10000,直 ...

  3. python的循环和选择

    一.python的选择结构: python的选择结构有两种选择结构一种是单选择(if...else)另一种则是多选择结构(if ...elif...elif) 下面用代码来实现: 1.if....el ...

  4. Python for 循环语句

    Python for 循环语句 Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串. 语法: for循环的语法格式如下: for iterating_var in sequenc ...

  5. Python的循环正确的操作使用方法详解

    要计算1+2+3,我们可以直接写表达式: >>> 1 + 2 + 3 6 要计算1+2+3+...+10,勉强也能写出来. 但是,要计算1+2+3+...+10000,直接写表达式就 ...

  6. python 6 循环

    循环 要计算1+2+3,我们可以直接写表达式: >>> 1 + 2 + 3 6 要计算1+2+3+...+10,勉强也能写出来. 但是,要计算1+2+3+...+10000,直接写表 ...

  7. python的循环语句

    python的循环语句有两种:for 和 while,for循环是对可迭代对象进行迭代并处理,因此for的对象是一个可以迭代的对象,而while循环的条件则是一个布尔值可以是一个返回布尔值的表达式. ...

  8. 图解python | for循环

    作者:韩信子@ShowMeAI 教程地址:http://www.showmeai.tech/tutorials/56 本文地址:http://www.showmeai.tech/article-det ...

  9. Python的循环

    循环是一个结构,导致一个程序要重复一定的次数 条件循环也一样,当条件变为假,循环结束 For循环 在python for循环遍历序列,如一个列表或一个字符. for循环语法:   ——for iter ...

  10. 在oj中Python的循环输入问题解决

    在oj中Python的循环输入问题解决 在makefile中定义逗号字符串和空格字符串 在linux服务器上面部署javaweb项目jar包 数据结构与算法之栈(Java与Python实现) 在oj中 ...

随机推荐

  1. python二叉树的遍历,递归和非递归及相关其它

    # encoding=utf-8class node(object): def __init__(self,data,left=None,right=None): self.data = data s ...

  2. 嵌入式选择与L1正则化

    http://blog.csdn.net/irene_loong/article/details/73741521

  3. .net 常用的插件列表

    1,.net 分布式Session 解决方案RedisSessionStateProvider 2,c# 表达式树查看工具 Expression Tree Visualizer 3,sqlbuilde ...

  4. 大数据之路- Hadoop环境搭建(Linux)

    前期部署 1.JDK 2.上传HADOOP安装包 2.1官网:http://hadoop.apache.org/ 2.2下载hadoop-2.6.1的这个tar.gz文件,官网: https://ar ...

  5. Zookeeper用来干什么?

    在Zookeeper的官网上有这么一句话:ZooKeeper is a centralized service for maintaining configuration information, n ...

  6. tensorflow 线性回归 iris

    线性拟合

  7. .DS_Store 文件是什么?Mac下面如何禁止.DS_Store生成

    .DS_Store是Mac OS保存文件夹的自定义属性的隐藏文件,如文件的图标位置或背景色,相当于Windows的desktop.ini. 1,禁止.DS_store生成:打开 “终端” ,复制黏贴下 ...

  8. bootstrap框架日期时间之年月选择及汉化

    ==>上次介绍了bootstrap框架日期时间 开始日期和结束日期选择 http://www.cnblogs.com/wjqblogs/p/4043198.html 今天又做了个只选择年月的日期 ...

  9. 1053 Path of Equal Weight (30)(30 分)

    Given a non-empty tree with root R, and with weight W~i~ assigned to each tree node T~i~. The weight ...

  10. BZOJ3230 相似子串[后缀数组+二分+st表]

    BZOJ3230 相似子串 给一个串,查询排名i和j的子串longest common suffix和longest common prefix 思路其实还是蛮好想的,就是码起来有点恶心.可以发现后缀 ...