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了,看见一个Python2写的百度词典,我也用Python 3 写了一个。真的很小巧,呵呵,很好的语言。
不知道怎么上传代码格式的,就上传文本了:
# -*- coding: utf8 -*-
import urllib.parse
import urllib.request
def search(word):
#word = input("输入你要查询的 ......
正则表达式是个魔鬼,也是个天使。在你没有掌握它之前,它是魔鬼,在你掌握它后,它是天使,但是,时
不时还是要跳出来,给你调皮捣蛋一番。
一个正则表达式就是由普通字符以及特殊字符组成的文字模式,该模式描述在查找文字主体时待
匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的 ......
>>> 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 ......
def
subString
(s,
length):
us = unicode(s, 'utf-8
')
gs =
us.encode('gb2312
')
n = int(length)
t = gs[:n]
while True
:
try
:
&nb ......
[原创]Python代码模块热更新机制实现(reload)
by AKara 2009-05-17 @ http://blog.csdn.net/akara @ akaras@163.com
---------------------------------------------------------------------
对一个游戏来说,无论是client或server都非常需要一套代码热更新的机制。
它能大大提高开发效率,又能超乎玩 ......