Python学习之循环

来源:互联网 发布:金融大数据就业前景 编辑:程序博客网 时间:2024/06/06 05:36

前面我们已经学习过基本语句和条件语句,从这儿开始,学习循环,主要学习两种循环,for循环while循环
编程语言就是要解决现实问题的,所以,条件语句,循环语句都是少不了要学习的。

首先来学习for循环

for循环

基本语法结构
for condition:
statement
说明,其中condition表示循环条件
statement表示循环语句

示例一,简单的for循环

在前面,想必或多或少的接触了for循环。
现在继续演示:
需求,打印出字符串“string”的每一个字母:

>>> for i in "string":...     print i... string>>> for i in "string":...     print i ,... s t r i n g>>> 

说明:以上示例说明了一个简单的for循环,其中如果print后面不加逗号,会自动换行,加逗号,表示不换行。
上面示例for循环的工作原理
首先“i”通过 访问对象“string”来获取字符串的位置,因为字符串是一个序列类型的对象,因此,“i”通过索引来输出对象“string”的每一个字符串。
也可以通过range()内置函数来访问“string”的每一个字符:
具体操作:

>>> test = "string">>> for i in range(len(test)):...     print i ,... 0 1 2 3 4 5>>> 

发现输出的并不是字符串中的字母,而是数值。
那么我们发现,测试代码中的len(test)是将字符串“string”转换为6,然后range(6)代表列表[0,1,2,3,4,5],那么“i就会根据列表中[0,1,2,3,4,5]的索引来获取“string”对应的每一个值。关于range( )的用法,后面会提到。
所以,上述中的循环应该这样做:

>>> test = "string">>> for i in range(len(test)):...     print test[i],... s t r i n g>>> 

示例二:列表中的for循环

需求,输出列表中的my name is xiaohuafen ,I am 23 years, I am a dog。

>>> list_name = ["My name is xiaohuafen ,","I am 23 years ,","I am dog !"]>>> for i in range(len(list_name)):...     print list_name[i],... My name is xiaohuafen , I am 23 years , I am dog !>>> 

依然是借用range( )函数来输出列表中的元素。

附加内容

range( )函数
在Python中,range函数的完整格式应该是range(start,stop[,step])
我们可以看到step是可选参数。

help(range)
Help on built-in function range in module builtin:

range(…)
range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.When step is given, it specifies the increment (or decrement).For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!These are exactly the valid indices for a list of 4 elements.

(END)

解释:
· start 开始数值,默认为0 ,如果这项不写,就是默认的start = 0.
· stop 结束数值,必写选项
· step 变化步长,默认为1,不能为0.
需要注意的事项:
1、此函数可以创建一个数字元素组成的列表。如我们之前的string,列表
2、常和for循环搭配使用
3、函数的参数必须是整数,默认从0 开始,返回值是一个列表。
4、step不能等于0 ,如果等于0 就会报错。
示例三
打印出0 到 9 之内的数字

>>> range(9)[0, 1, 2, 3, 4, 5, 6, 7, 8]>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(0,10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(0,10,1)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> 

思考,如果我们要输出0 到-9该怎么办

>>> range(-10)[]>>> range(0,-10)[]>>> range(0)[]>>> 

发现都不行,那么我们加入step试试

>>> range(0,-10,-1)[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]>>> 

思考,如果我们要输出-9到0该怎么办

>>> range(-9,1)[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0]>>> 

关于具体怎么实现的,自己去思考哦,可不要偷懒。
那么我们使用内置函数range( )来实现一个需求

需求,找到自然数100 以内当中的所有偶数

>>> range(0,100,2)[0, 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, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]>>> 

使用条件语句实现。

>>> oushu = []>>> for i in range(100):...     if i % 2 == 0:...         oushu.append(i)... >>> print oushu[0, 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, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]>>> 

结果是一样的。但是使用range函数条件语句简洁的多。

思考,找出100以内的所有的奇数

>>> range(1,100,2)[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, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]>>> 

条件语句代码

>>> jishu  = []>>> for i in range(100):...     if i % 2 != 0:...          jishu.append(i)... >>> print jishu[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, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]>>> 

到这里,range函数就告一段落了。

继续学习for循环:
思考,如何找出100以内能被3 整除的正整数

#!/bin/bash/env python#coding:utf-8##创建一个列表用来存储被3整除的数test = []##使用for循环遍历100以内的正整数for i in range(1100):##使用条件语句判断能被3整除的数    if i % 3 == 0:##如果能被整除,则将这个数追加到test中        test.append(i)#打印输出testprint test~                                                         ~          

输出结果
[root@python ~]# python 3test.py
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]

不过感觉是不是有点麻烦,要是使用range ( )函数,会不会很方便呢。

>>> range(3,100,3)[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]>>> 

果然,很方便。
for的对象
既然for循环遍历的时候是通过索引来找对象中的元素,那么只要是具有序列的对象,都可以被for遍历。
字符串

>>> for i in "this is test":...     print i,... t h i s   i s   t e s t>>> 

列表

>>> for i in list_test:...     print i,... t h i s   i s   t e s t>>> 

集合

>>> set_test = set(test)>>> for i in set_test:...     print i,...   e i h s t

懵了吧,别担心,想想集合的三大特性是什么呢?记起来就懂了,记不起来的,去前面看Python学习之集合

元组

>>> tuple_test = tuple(test)>>> tuple_test('t', 'h', 'i', 's', ' ', 'i', 's', ' ', 't', 'e', 's', 't')>>> for i in tuple_test:...     print i,... t h i s   i s   t e s t>>> 

字典:

>>> net = {"search":"baidu","website":"https://www.baidu.com","navi":"google","look":"news"}>>> for i in net:...     print i,"----->",net[i]... website -----> https://www.baidu.comnavi -----> googlesearch -----> baidulook -----> news>>> 

这里只是针对遍历Key进行查找,对应到value,那么我们再遍历key的时候,同时遍历出value

之前学过,我们获得字典键值的函数有items/iteritems/keys/iterkeys/values/itervalues,通过这些函数得到的都是键或者值得列表。

一一测试

>>> net{'website': 'https://www.baidu.com', 'navi': 'google', 'search': 'baidu', 'look': 'news'}>>> for i in net:...     print i,net[i]... website https://www.baidu.comnavi googlesearch baidulook news>>> for k,v in net.items():...     print k,v... website https://www.baidu.comnavi googlesearch baidulook news>>> for k,v in net.iteritems():...     print k,v... website https://www.baidu.comnavi googlesearch baidulook news>>> for k in net.keys():...     print k,net[k]... website https://www.baidu.comnavi googlesearch baidulook news>>>>>> for k in net.iterkeys():...     print k,net[k]... website https://www.baidu.comnavi googlesearch baidulook news>>> >>> for v in net.values():...     print v... https://www.baidu.comgooglebaidunews>>> for v in net.itervalues():...     print v... https://www.baidu.comgooglebaidunews>>> 

20170509关于for循环补充

由于昨晚没有将for循环学习完,所以今天就接着继续学习。

zip( )函数

在Python中,迭代是使用比较频繁的,尤其是在for循环
for循环表现之一就是迭代,从序列对象中获取一定数量的元素。

但在现实生活中,迭代并没有那么简单。

比如,有两个列表
a = [1,2,3,4,5]
b = [9,8,7,6,5]
那么我们如何实现a[i] + b[i] 呢?

>>> a = [1,2,3,4,5]>>> b = [9,8,7,6,5]>>> c = []>>> for i in range(len(a)):...     c.append(a[i] + b[i])... >>> print c[10, 10, 10, 10, 10]>>> 

看起来,for循环的解决方法还是很不错,但是,Python总不会局限于一个解决之道。所以,Python又引入了一个内置函数zip ( )
那么内置函数zip( )该如何使用呢。

help(zip)
Help on built-in function zip in module builtin:

zip(…)
zip(seq1 [, seq2 […]]) -> [(seq1[0], seq2[0] …), (…)]

Return a list of tuples, where each tuple contains the i-th elementfrom each of the argument sequences.  The returned list is truncatedin length to the length of the shortest argument sequence.

(END)
解释:返回元组中的一个列表,其中每个元组包含第i个元素 从每个参数序列。 返回的列表被截断长度到最短参数序列的长度。

>>> a[1, 2, 3, 4, 5]>>> b[9, 8, 7, 6, 5]>>> zip(a,b)[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)]>>> 

最后一句话的意思是,如果两个序列的长度不同,那么返回的列表就以最短的列表中的元素长度为准。

验证:

>>> a = ['a','b','c']>>> b = ['z','y','x','w']>>> zip(a,b)[('a', 'z'), ('b', 'y'), ('c', 'x')]>>> 

继续测试一个:

>>> a = {"baidu","google"}>>> b = {"https://www.baidu.com","https://www.google.com"}>>> zip(a,b)[('baidu', 'https://www.baidu.com'), ('google', 'https://www.google.com')]>>> 

上面的测试,a,b是字典吗?当然不是哈
字典应该是长下面这个样子的。

>>> dict1 = {"baidu":"https://www.baidu.com"}>>> dict2 = {"google":"https://www.google.com"}>>> zip(dict1,dict2)[('baidu', 'google')]>>> 

发现,如果是字典使用zip ( )函数,那么只会返回字典中的Key
注意,特殊情况:当参数是一个序列时生成的结果

>>> a['a', 'b', 'c']>>> zip(a)[('a',), ('b',), ('c',)]>>> 

因为只提供了一个参数,所以,列表中的元组就是一个元素,此时元组中的元素后面还有一个半角逗号。

那么,回到我们起初做的将a = [1,2,3,4,5] b = [9,8,7,6,5]中对应的元素相加可以用zip( )函数实现
代码如下:

>>> a = [1,2,3,4,5]>>> b = [9,8,7,6,5]>>> c = []>>> for x,y in zip(a,b):...     c.append(x+y)... >>> print c[10, 10, 10, 10, 10]>>> 

思考,如果两个列表元素不同,并且当中的数据类型也不相同该怎么办?

假如: a = [1,2,3,4,5]
b = [“baidu”,”https://www.baidu.com“,”navi”]

首先比较一下长度:在这里使用三目运算符,复习一下

>>> a = [1,2,3,4,5]>>> b = ["baidu","https://www.baidu.com","navi"]>>> lenth = len(a) if len(a) < len(b) else len(b)>>> print lenth3>>> 

使用for循环将两个列表中的元素相加:

>>> a[1, 2, 3, 4, 5]>>> b['baidu', 'https://www.baidu.com', 'navi']>>> c = []>>> for i in range(lenth):...     c.append(a[i] + ":" + b[i])... Traceback (most recent call last):  File "<stdin>", line 2, in <module>TypeError: unsupported operand type(s) for +: 'int' and 'str'>>> 

报错了,提示信息说不支持的操作int和str类型连接
很明显,我们前面遇到过这种报错信息,所以进行类型转换

>>> a[1, 2, 3, 4, 5]>>> b['baidu', 'https://www.baidu.com', 'navi']>>> c = []>>> for i in range(lenth):...     c.append(str(a[i]) + ":" + b[i])... >>> print c['1:baidu', '2:https://www.baidu.com', '3:navi']>>> 

使用zip( )对应连接

>>> a[1, 2, 3, 4, 5]>>> b['baidu', 'https://www.baidu.com', 'navi']>>> c = []>>> for x,y in zip(a,b):...     c.append(str(x) + ":" + y)... >>> print c['1:baidu', '2:https://www.baidu.com', '3:navi']>>> 

显然,以上两种写法相对而言,zip( )的写法要相对简单。
补充
zip( )还可以将元组中的元素单独提取出来

>>> c = zip(a,b)>>> c[(1, 'baidu'), (2, 'https://www.baidu.com'), (3, 'navi')]>>> zip(*c)[(1, 2, 3), ('baidu', 'https://www.baidu.com', 'navi')]>>> 

思考,如何将字典 test = {“name”:”baidu”,”website”:”https://www.baidu.com“,”navi”:”baiduyixia”} 转换成demo = {“baidu”:”name”,”https://www.baidu.com“:”website”,”baiduyixia”:”navi”}
方法一,采用for循环

>>> test = {"name":"baidu","website":"https://www.baidu.com","navi":"baiduyixia"}>>> demo = {}>>> for k,v in test.items():...     demo[v] = k... >>> print demo{'baidu': 'name', 'https://www.baidu.com': 'website', 'baiduyixia': 'navi'}>>> 

方法二,采用zip( )

>>> test{'website': 'https://www.baidu.com', 'navi': 'baiduyixia', 'name': 'baidu'}>>> dict(zip(test.values(),test.keys())){'baidu': 'name', 'https://www.baidu.com': 'website', 'baiduyixia': 'navi'}>>> 

enumerate( )函数

本来可以通过for i in range(len(list))的方式得到list中的每一个元素,但是同时要得到索引和元素怎么办?

>>> week = ["monday","sunday","friday"]>>> for i in range(len(week)):...     print week[i] + " is " + str(i)... monday is 0sunday is 1friday is 2>>> 

用for循环可以,但是Python提供了 一个内建函数enumerate( )可以很方便的实现此功能。

>>> week['monday', 'sunday', 'friday']>>> for (i,day) in enumerate(week):...     print day + " is " + str(i)... monday is 0sunday is 1friday is 2>>> 

查看enumerate( )函数的帮助文档

help(enumerate)

Help on class enumerate in module builtin:

class enumerate(object)
| enumerate(iterable[, start]) -> iterator for index, value of iterable
|
| Return an enumerate object. iterable must be another object that supports
| iteration. The enumerate object yields pairs containing a count (from
| start, which defaults to zero) and a value yielded by the iterable argument.
| enumerate is useful for obtaining an indexed list:
| (0, seq[0]), (1, seq[1]), (2, seq[2]), …
|
| Methods defined here:
:

解释:
enumerate(iterable[, start]),中两个参数,第一个参数是可迭代的,第二个参数可选,指定从第几个索引开始,
返回一个枚举对象。 对象必须是可迭代的,枚举对象产生包含计数(从
| start,其默认为零)和由iterable参数产生的值。
| 枚举对于获取索引列表很有用:
练习:

>>> seasons = ["Spring","Summer","Fall","Winter"]>>> list(enumerate(seasons))[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]>>> list(enumerate(seasons,start = 5))[(5, 'Spring'), (6, 'Summer'), (7, 'Fall'), (8, 'Winter')]>>>  

列表解析

需求,得到1–9的平方数

>>> import math>>> for i in range(1,10):...     print i * i... 149162536496481

列表实现

>>> pingfang = [i ** 2 for i in range(1,10)]>>> print pingfang[1, 4, 9, 16, 25, 36, 49, 64, 81]>>> 

去掉元素前后的空格。

>>> name = ["    wang","li","xiao    "]>>> sname = [i.strip() for i in name]>>> print sname['wang', 'li', 'xiao']>>> 

关于for循环就学习完了,明天学习while循环
完成时间:

2017 05 09
23:42

1 0
原创粉丝点击