Python 学习笔记(十一)Python语句(二)
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
ali
>>> t =tuple(lst)
>>> t
('baidu', 'google', 'ali')
>>> for i in t: #用变量i遍历元组,将每个元素打印出来
... print i
...
baidu
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语句(二)的更多相关文章
- python学习笔记(十一)-python程序目录工程化
在一个程序当中,一般都会包含文件夹:bin.conf.lib.data.logs,以及readme文件. 所写程序存放到各自的文件夹中,如何进行串联? 首先,通过导入文件导入模块方式,引用其他人写好的 ...
- python 学习笔记 9 -- Python强大的自省简析
1. 什么是自省? 自省就是自我评价.自我反省.自我批评.自我调控和自我教育,是孔子提出的一种自我道德修养的方法.他说:“见贤思齐焉,见不贤而内自省也.”(<论语·里仁>)当然,我们今天不 ...
- python学习笔记(一):python简介和入门
最近重新开始学习python,之前也自学过一段时间python,对python还算有点了解,本次重新认识python,也算当写一个小小的教程.一.什么是python?python是一种面向对象.解释型 ...
- python 学习笔记一——Python安装和IDLE使用
好吧,一直准备学点啥,前些日子也下好了一些python电子书,但之后又没影了.年龄大了,就是不爱学习了.那就现在开始吧. 安装python 3 Mac OS X会预装python 2,Linux的大多 ...
- python学习笔记(python简史)
一.python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum) 目前python主要应用领域: ·云计算 ·WEB开发 ·科学运算.人工智能 ·系统运维 ·金融:量化交 ...
- python学习笔记之——python模块
1.python模块 Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句. 模块让你能够有逻辑地组织你的 Python ...
- Python学习笔记 - day12 - Python操作NoSQL
NoSQL(非关系型数据库) NoSQL,指的是非关系型的数据库.NoSQL有时也称作Not Only SQL的缩写,是对不同于传统的关系型数据库的数据库管理系统的统称.用于超大规模数据的存储.(例如 ...
- python学习笔记(1)--python特点
python诞生于复杂的信息系统时代,是计算机时代演进的一种选择. python的特点,通用语言,脚本语言,跨平台语言.这门语言可以用于普适的计算,不局限于某一类应用,通用性是它的最大特点.pytho ...
- python 学习笔记十一 SQLALchemy ORM(进阶篇)
SqlAlchemy ORM SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据A ...
- 【Python学习笔记】with语句与上下文管理器
with语句 上下文管理器 contextlib模块 参考引用 with语句 with语句时在Python2.6中出现的新语句.在Python2.6以前,要正确的处理涉及到异常的资源管理时,需要使用t ...
随机推荐
- 简单工厂模式的C++、Java实现
1.简单工厂模式UML UML如下: 图1. 简单工厂模式UML 2.C++实现 类视图如下: 图2. C++实现简单工厂模式类视图 其中,SimpleFactory实现为: Product * Si ...
- Python入门-初始面向对象
之前我们代码基本上都是面向过程的,今天我们就来初始一下python中一个重要的内容:面向对象 一.面向对象和面向过程(重点理解) 1.面向过程: 一切以事物的流程为核心. 核心是"过程&qu ...
- html+css中常见的浏览器兼容性处理
1.居中问题 div里的内容,IE默认为居中,而FF默认为左对齐,可以尝试增加代码margin: 0 auto; 2.高度问题 两上下排列或嵌套的div,上面的div设置高度(height),如果di ...
- vs2010开发activex(MFC)控件/ie插件(二):js传参数
原文:http://blog.csdn.net/yhhyhhyhhyhh/article/details/50802075 js传参数给activex控件. 过程为:js变量通过activex类的属 ...
- listview cacheColorHint,listSelector属性
ListView是常用的显示控件,默认背景是和系统窗口一样的透明色,如果给ListView加上背景图片,或者背景颜色时,滚动时listView会黑掉, 原因是,滚动时,列表里面的view重绘时,用的依 ...
- 基于容器微服务的PaaS云平台设计(一) 实现容器微服务和持续集成
版权声明:本文为博主原创文章,欢迎转载,转载请注明作者.原文超链接 ,博主地址:http://www.cnblogs.com/SuperXJ/ 前言:关于什么是容器微服务PaaS和容器微服务PaaS的 ...
- 基础JavaScript练习(一)
任务目的 学习与实践JavaScript的基本语法.语言特性 初步了解JavaScript的事件是什么 初步了解JavaScript中的DOM是什么 任务描述 如图,模拟一个队列,队列的每个元素是一个 ...
- How I explained OOD to my wife
Introduction My wife Farhana wants to resume her career as a software developer (she started her car ...
- SpringBoot页面访问处理
SpringBoot页面访问处理 1.介绍 Springboot推荐使用thymeleaf模板引擎搭载html页面实现jsp动态渲染效果,因此这里才会用该种方案进行. 2.集成步骤 引入thymele ...
- 修改容器的hosts文件
修改容器的hosts文件 1.介绍 docker容器中的hosts文件虽然在宿主机磁盘上/var/lib/docker/containers/xxx/hosts中,但是修改该文件是无效的,需要通过其他 ...