如何获取列表的索引值呢?
ints = [8, 23, 45, 12, 78]
如果像C或者PHP那样可以加入一个状态变量,这里使用Python最好的选择就是用内建函数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 += 1enumerate会将数组或列表组成一个索引序列。使我们再获取索引和索引内容的时候更加方便如下:
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以上就是如何在循环中获取索引(数组下标)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号