range()、list与for

range用法

使用python的人都知道range()函数很方便,今天再用到他的时候发现了很多以前看到过但是忘记的细节。

这里记录一下:

range(1,5)#代表从1到5(不包含5)
[1,2,3,4]
range(1,5,2)#代表从1到5,间隔2(不包含5)
[1,3]
range(5)#代表从0到5(不包含5)
[0,1,2,3,4]

再看看list的操作:

array= [1,2,5,3,6,8,4]
#其实这里的顺序标识是
[1,2,5,3,6,8,4]
(0123456)
(-7,-6,-5,-4,-3,-2,-1)
 
array[0:]#列出0以后的
[1,2,5,3,6,8,4]
array[1:]#列出1以后的
[2,5,3,6,8,4]
array[:-1]#列出-1之前的
[1,2,5,3,6,8]
array[3:-3]#列出3到-3之间的
[3]

for loop

the_count = [1, 2, 3, 4, 5]

fruits = ["apples", "oranges", "pears", "apricots"]
change = [1, "pennies", 2, "dimes", 3, "quarters"]

for i in elements:

print "Element was: %d" % i</pre><br/>输出</div><div><code class="python plain" style="white-space:pre-wrap; margin:0px!important; padding:0px!important; border:0px!important; bottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; outline:0px!important; overflow:visible!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,"Bitstream Vera Sans Mono","Courier New",Courier,monospace!important; min-height:inherit!important"/><pre code_snippet_id="380742" snippet_file_name="blog_20140607_2_157426" name="code" class="python">This is count 1

This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got "pennies"
I got 2
I got "dimes"
I got 3
I got "quarters"
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

<br/><br/>
文章导航