python 筆記 for loop and extend, append

list.append(item)

 

list.extend(sequence)

http://docs.python.org/tutorial/datastructures.html

 

http://docs.python.org/library/functions.html 這幾天看一下

python howto

恩。python documentation 確實很好很強大啊!

 

list.append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].
a[len(a):] 是一個list,slice得到的一個list,相當於把這一段截取出來的list,要是等於一個list b,相當於在a的末尾添加了b,但是b整個是一個元素。
>>> c.append([1,2,3])
>>> c
[1, 2, 3, 4, [1, 2, 3]]
list.extend(L)
Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

添加L中的元素,延長a

 

 

For loop, for(i=0; i<n; i++) in python is for i in range(0, n)

對於步長爲2,則 for i in range(0, n, 2):  range 函數可以改變步長! 不用 i += 2, Mark一下。

 

for i in range(0,10,2):

    print i

 

0

2

4

6

8

 

 

比如尋找素數的程序。那麼,尋找是不是被整除的時候,除了2 之外,可以從3開始,步長爲2的去搜索。直到[sqrt(prime_n)](就是int(sqrt(prime_n)), 高斯函數)爲止。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章