码迷,mamicode.com
首页 > 其他好文 > 详细

Traversing a list

时间:2014-07-13 19:38:51      阅读:324      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   os   2014   for   

The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings:

bubuko.com,布布扣                       

This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the functions range and len:

 bubuko.com,布布扣

This loop traverses the list and updates each element. len returns the number of elements in the list. range returns a list of indices from 0 to n-1, where n is the length of the list. each time through the loop I gets the index of the next element. The assignment statement in the body uses I to read the old value of the element and to assign the new value.

A for loop over an empty list never executes the body:

 bubuko.com,布布扣

Although a list can contain another list, the nested list still counts a single element. The length of this list is four:

bubuko.com,布布扣 

 

from Thinking in Python

Traversing a list,布布扣,bubuko.com

Traversing a list

标签:style   blog   http   os   2014   for   

原文地址:http://www.cnblogs.com/ryansunyu/p/3841087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!