易截截图软件、单文件、免安装、纯绿色、仅160KB

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


相关文档:

python处理XML

基本上都是使用python来解析xml文件的。
比如我要将内容为
<?xml version="1.0" encoding="utf-8"?>
    <root>
        <book isbn="34909023">
            <author>
 &n ......

python中%符号详解

%a 星期几的简写
%A 星期几的全称
%b 月分的简写
%B 月份的全称
%c 标准的日期的时间串
%C
年份的后两位数字
%d 十进制表示的每月的第几天
%D 月/天/年
%e 在两字符域中,十进制表示的每月的第几天
%F
年-月-日
%g 年份的后两位数字,使用基于周的年
%G 年分,使用基于周的年
%h 简写的月份名 ......

关于Python中时间与字符串直接的转换

>>> import time
>>> import datetime
>>>
now = time.localtime()
>>> now
(2006, 4, 30, 18, 7, 35,
6, 120, 0)
>>> type(now)
<type 'time.struct_time'>
>>>
str_now = time.strftime("%m/%d/%Y %X", now )
>>>
str_n ......

python中如何判断一个变量的数据类型?(原创)

import types
type(x) is types.IntType # 判断是否int 类型
type(x) is types.StringType #是否string类型
.........
--------------------------------------------------------
超级恶心的模式,不用记住types.StringType
import types
type(x) == types(1) # ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号