For 循环语句

基础知识

for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

语法:

for 循环规则:

  do sth

 >>> for i in "python" : #用i这个变量遍历这个字符串的每一个字符
... print i #将遍历的字符打印出来
...
p
y
t
h
o
n
>>> lst =["baidu","google","ali"]
>>> for i in lst: #用变量i遍历这个列表,将每个元素打印出来
... print i
...
baidu
google
ali
>>> t =tuple(lst)
>>> t
('baidu', 'google', 'ali')
>>> for i in t: #用变量i遍历元组,将每个元素打印出来
... print i
...
baidu
google
ali
>>> d =dict([("lang","python"),("website","baidu"),("city","beijing")])
>>> d
{'lang': 'python', 'website': 'baidu', 'city': 'beijing'}
>>> for k in d: #用变量k遍历这个字典,将每个key打印出来
... print k
...
lang
website
city
>>> for k in d: #用变量k遍历字典d
... print k,"-->",d[k] #将key值和value值打印出来
...
lang --> python
website --> baidu
city --> beijing
>>> d.items() #以列表返回可遍历的(键, 值) 元组
[('lang', 'python'), ('website', 'baidu'), ('city', 'beijing')]
>>> for k,v in d.items(): #用key value遍历d.items()的元组列表
... print k,"-->",v #取得key ,value
...
lang --> python
website --> baidu
city --> beijing
>>> for k,v in d.iteritems(): iteritems 返回的是迭代器 推荐使用这个
... print k,v
...
lang python
website baidu
city beijing
>>> d.itervalues() 返回的是迭代器
<dictionary-valueiterator object at 0x0000000002C17EA8>
>>>

判断对象是否可迭代

 >>> import collections  #引入标准库
>>> isinstance(321,collections.Iterable) #返回false,不可迭代
False
>>> isinstance([1,2.3],collections.Iterable) #返回true,可迭代
True
 >>> l =[1,2,3,4,5,6,7,8,9]
>>> l[4:]
[5, 6, 7, 8, 9]
>>> for i in l[4:]: #遍历4以后的元素
... print i
...
5
6
7
8
9
>>> help(range) #函数可创建一个整数列表,一般用在 for 循环中
Help on built-in function range in module __builtin__: range(...)
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers #计数从 start 开始,计数到 stop 结束,但不包括 stop,step:步长,默认为1 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. >>> range(9)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> range(2,8)
[2, 3, 4, 5, 6, 7]
>>> range(1,9,3)
[1, 4, 7]
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(0,9,2)
[0, 2, 4, 6, 8]
>>> for i in range(0,9,2):
... print i
...
0
2
4
6
8
>>>
 #! /usr/bin/env python
#coding:utf-8 aliquot =[] #创建一个空的列表 for n in range(1,100): #遍历1到100 的整数
if n %3==0: #如果被3整除
aliquot.append(n) #将n值添加到列表中 print aliquot

zip() 函数

函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

返回一个列表,这列表是以元组为元素

 >>> 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])
>>> for i in range(len(a)):
... c.append(a[i]+b[i])
...
>>> c
[10, 10, 10, 10, 10]
>>> 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 element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence. >>> 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)]
>>> c =[1,2,3]
>>> zip(c,b)
[(1, 9), (2, 8), (3, 7)]
>>> zip(a,b,c)
[(1, 9, 1), (2, 8, 2), (3, 7, 3)]
>>> d=[]
>>> for x,y in zip(a,b):
... d.append(x+y)
...
>>> d
[10, 10, 10, 10, 10]
>>> r =[(1,2),(3,4),(5,6),(7,8)]
>>> zip(*r)
[(1, 3, 5, 7), (2, 4, 6, 8)]
>>>

enumerate()函数

函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

语法:

enumerate(sequence, [start=0])

sequence -- 一个序列、迭代器或其他支持迭代对象

start -- 下标起始位置。

返回值: 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:
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __iter__(...)
| x.__iter__() <==> iter(x)
|
| next(...)
| x.next() -> the next value, or raise StopIteration
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T >>> weeks =["sun","mon","tue","web","tue","fri","sta"]
>>> for i,day in enumerate(weeks):
... print str(i)+":"+day
...
0:sun
1:mon
2:tue
3:web
4:tue
5:fri
6:sta
>>> for i in range(len(weeks)):
... print str(i)+":"+weeks[i]
...
0:sun
1:mon
2:tue
3:web
4:tue
5:fri
6:sta
>>> raw ="Do you love canglaoshi? canglaoshi is a good teacher."
>>> raw_lst =raw.split(" ")
>>> raw_lst
['Do', 'you', 'love', 'canglaoshi?', 'canglaoshi', 'is', 'a', 'good', 'teacher.']
>>> for i,w in enumerate(raw_lst):
... if w =="canglaoshi":
... raw_lst[i]="luolaoshi"
...
>>> raw_lst
['Do', 'you', 'love', 'canglaoshi?', 'luolaoshi', 'is', 'a', 'good', 'teacher.']
>>> for i,w in enumerate(raw_lst):
... if "canglaoshi" in w:
... raw_lst[i]="luolaoshi"
...
>>> raw_lst
['Do', 'you', 'love', 'luolaoshi', 'luolaoshi', 'is', 'a', 'good', 'teacher.']
>>> a =range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> s =[]
>>> for i in a:
... s.append(i*i)
...
>>> s
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> b = [i*i for i in a] #列表解析
>>> b
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> c = [i*i for i in a if i%3==0] #列表解析,加入限制条件
>>> c
[0, 9, 36, 81]
>>>

列表解析

Python 学习笔记(十一)Python语句(二)的更多相关文章

  1. python学习笔记(十一)-python程序目录工程化

    在一个程序当中,一般都会包含文件夹:bin.conf.lib.data.logs,以及readme文件. 所写程序存放到各自的文件夹中,如何进行串联? 首先,通过导入文件导入模块方式,引用其他人写好的 ...

  2. python 学习笔记 9 -- Python强大的自省简析

    1. 什么是自省? 自省就是自我评价.自我反省.自我批评.自我调控和自我教育,是孔子提出的一种自我道德修养的方法.他说:“见贤思齐焉,见不贤而内自省也.”(<论语·里仁>)当然,我们今天不 ...

  3. python学习笔记(一):python简介和入门

    最近重新开始学习python,之前也自学过一段时间python,对python还算有点了解,本次重新认识python,也算当写一个小小的教程.一.什么是python?python是一种面向对象.解释型 ...

  4. python 学习笔记一——Python安装和IDLE使用

    好吧,一直准备学点啥,前些日子也下好了一些python电子书,但之后又没影了.年龄大了,就是不爱学习了.那就现在开始吧. 安装python 3 Mac OS X会预装python 2,Linux的大多 ...

  5. python学习笔记(python简史)

    一.python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum) 目前python主要应用领域: ·云计算 ·WEB开发 ·科学运算.人工智能 ·系统运维 ·金融:量化交 ...

  6. python学习笔记之——python模块

    1.python模块 Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句. 模块让你能够有逻辑地组织你的 Python ...

  7. Python学习笔记 - day12 - Python操作NoSQL

    NoSQL(非关系型数据库) NoSQL,指的是非关系型的数据库.NoSQL有时也称作Not Only SQL的缩写,是对不同于传统的关系型数据库的数据库管理系统的统称.用于超大规模数据的存储.(例如 ...

  8. python学习笔记(1)--python特点

    python诞生于复杂的信息系统时代,是计算机时代演进的一种选择. python的特点,通用语言,脚本语言,跨平台语言.这门语言可以用于普适的计算,不局限于某一类应用,通用性是它的最大特点.pytho ...

  9. python 学习笔记十一 SQLALchemy ORM(进阶篇)

    SqlAlchemy ORM SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据A ...

  10. 【Python学习笔记】with语句与上下文管理器

    with语句 上下文管理器 contextlib模块 参考引用 with语句 with语句时在Python2.6中出现的新语句.在Python2.6以前,要正确的处理涉及到异常的资源管理时,需要使用t ...

随机推荐

  1. flask接收前台的ajax的post数据

    html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8& ...

  2. Django 模型层之单表操作

    一.单表操作之创建表 在app的models.py文件中创建模型: from django.db import models class Book(models.Model): id = models ...

  3. 虽然我们可能不想对元素应用3D变换,可我们一样可以开启3D引擎

    例如我们可以用transform: translateZ(0); 来开启硬件加速 ..cube {-webkit-transform: translateZ(0);-moz-transform: tr ...

  4. 前端学习之路之CSS (一)

    Infi-chu: http://www.cnblogs.com/Infi-chu/ 简介:    CSS 指层叠样式表 (Cascading Style Sheets)    样式定义如何显示 HT ...

  5. 003客户端负载均衡Ribbon & 短路器Hystrix

    1.POM配置 和普通Spring Boot工程相比,仅仅添加了Eureka.Ribbon.Hystrix依赖和Spring Cloud依赖管理 <dependencies> <!- ...

  6. Android PopupWindow显示位置设置

    当点击某个按钮并弹出PopupWindow时,PopupWindow左下角默认与按钮对齐,但是如果PopupWindow是下图的那样,会发 生错位的情况,尤其是不同尺寸的平板上,那错位错的不是一般的不 ...

  7. Vue2.0中的Ajax请求

    Vue可以借助于vue-resource来实现Ajax请求 http请求报文 浏览器与服务器数据交互是遵循http协议的,当浏览器要访问服务器的时候,浏览器需要将相关请求数据提交给服务器. 格式分为: ...

  8. qt 创建资源文件

    我们编写的gui可能需要一些额外的资源(比如贴图用的图片),可用资源文件统一管理.以下以图片为例. 用qt creator 打开工程,为工程新建资源文件: 命名为“项目名.prc”,(此处为“cloc ...

  9. QT5.3 杂记

    Qt5下,QWidget系列从QtGui中被剥离出去,成为单独的QtWidget模块.随着Qt Quick2的引入,QtDeclarative也逐渐和QWidget系列也脱离关系. 最终:在Qt5下的 ...

  10. SVN升级到1.8后 Upgrade working copy

    SVN升级到1.8后没法用了,不能提交,提示说要SVN Upgrade working copy, 但是半天在根目录和.svn所在文件夹上面右键都没有找到这个菜单. 坑爹的…… 最后找到解决办法是:重 ...