python enumerate用法
python cookbook
Recipe 2.5. Counting Lines in a File
,
今日发现一个新函数
enumerate
。一般情况下对一个列表或数组既要遍历索引又要遍历元素时,会这样写:
for
i
in
range
(0
,
len
(list
)):
print
i
,
list
[
i
]
但是这种方法有些累赘,使用
内置enumerrate函数会有更加直接,优美的做法,先看看enumerate的定义:
def
enumerate
(collection
):
'Generates an indexed series:
(0,coll[0]), (1,coll[1]) ...'
i
=
0
it
=
iter
(collection
)
while
1
:
yield
(i
,
it
.
next
())
i
+=
1
enumerate会将数组或列表组成一个索引序列。使我们再获取索引和索引内容的时候更加方便如下:
for
index
,
text
in
enumerate
(list
)):
print
index
,
text
在
cookbook里介绍,如果你要计算文件的行数,可以这样写:
count
=
len
(open
(thefilepath
,
‘
rU
’
).
readlines
())
前面这种方法简单,但是可能比
较慢,当文件比较大时甚至不能工作,下面这种循环读取的方法更合适些。
Count
=
-
1
For
count
,
line
in
enumerate
(open
(thefilepath
,
‘
rU
’
)):
Pass
Count
+=
1
相关文档:
ubuntu10.05出来了这两天一直在折腾,显示wubi无反应,然后从硬盘安装期间又遇到grub错误等问题。安装成功后搞个中文输入法就老半天,最后使用Pinyin这个还算好用,有点想搜狗就是没什么词库。最恶心的还是vim的问题,用apt-get install vim装的vim不支持系统剪切板,只好从源代码编译,可是我尝试了很多次总是没有python支 ......
python对多国语言的处理是支持的很好的,它可以处理现在任意编码的字符,这里深入的研究一下python对多种不同语言的处理。
有一点需要清楚的是,当python要做编码转换的时候,会借助于内部的编码,转换过程是这样的:
原有编码 -> 内部编码 ->
目 ......
基本上都是使用python来解析xml文件的。
比如我要将内容为
<?xml version="1.0" encoding="utf-8"?>
<root>
<book isbn="34909023">
<author>
&n ......
很长的一段代码,但很清楚。哈哈。
import os
from time import strftime
stamp=strftime("%Y-%m-%d %H:%M:%S")
logfile = 'F:\\test\\m-php-framework\\tmp\logs\\error_report.log'
path = 'F:\\test\\'
files = os.listdir(path)
bytes = 0
numfiles = 0
for f in files:
if f.startswith('t'): ......
Python MySQLdb 查询返回字典结构 smallfish
MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。
默认程序:
import MySQLdb
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', d ......