1. 程式人生 > >《笨方法學 Python 3》32. for 迴圈和列表

《笨方法學 Python 3》32. for 迴圈和列表

        我們在開始使用 for 迴圈前,你需要在某個位置存放迴圈的結果。最好的方法就是使用列表(list),顧名思義,它就是一個從頭到尾按順序存放東西的容器。

        首先我們看看如何建立列表:

hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]

        就是以" [ "開頭,以“ ] ”結尾,中間是你要放入列表的東西,用“ , ”隔開。這就是列表(list),然後Python接受這個列表以及裡面所有的內容,將其賦值給一個變數。

基礎練習:

        現在我們講使用 for 迴圈建立一些列表,然後將它們打印出來:

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

# this first kind of for-loop goes through a list.///第一種for迴圈會通過一個列表
for number in the_count:
	print(f"This is count {number}")

#same as above.///同上
for fruit in fruits:
	print(f"A fruit of type: {fruit}")

#also we can go through mixed lists too.///我們也可以通過混合列表
#notice we have to use {} since we don't know what's in items.///注意,我們必須使用{}因為我們不知道里面是什麼東西
for i in change:
	print(f"I got {i}")

#we can also build lists, first start with an empty one.///我們也可以建立列表,首先從一個空的開始
elements = []

#then use the range function to do 0 to 5 counts.///然後使用range函式來做0到5計數
for i in range(0,6):
	print(f"Adding {i} to the list.")
	#append is a function that lists understand.///append是一個列表理解的函式
	elements.append(i)
	
# now we can print them out too.///現在我們也可以把它們打印出來
for i in elements:
	print(f"Element was: {i}")

結果:

知識點:

1.  range() 函式:

  • range() 函式可以建立一個整數列表,一般用在 for 迴圈中。
  • 語法:range(start,stop,step) 
  • start:start 是計數開始,一般預設為0,例如 range(5)的意思就是 range(0, 5);
  • stop:stop 是計數結束,但不包含 stop,例如 range(0,5)是[0, 1, 2, 3, 4],不包含[5];
  • step:step 是步長(就是兩數之間間隔),一般預設為1,例如 range(0,5)的意思就是 range(0, 5, 1);

例項: range(25) = range(0, 25)  :[0, 1, 2, 3, ...25]

            range(0,25,5)  :[0, 5, 10, 15, 20, 25]

2.  append()函式:

  • append() 函式可以在列表的尾部追加引數,例如:

  • append()  1次只能追加1個引數 ,它可以追加任何型別的引數
  • 還有一個expend() 函式也可以在列表後追加引數,但是它追假的引數型別必須是list,也就是在原來的list的尾部追加list。

END!!!