笨辦法學Python(三十二)

來源:互聯網
上載者:User

標籤:element   關於   his   hat   bsp   分割   hang   change   ber   

習題 32: 迴圈和列表

    現在你應該有能力寫更有趣的程式出來了。如果你能一直跟得上,你應該已經看出將“if 語句”和“布林運算式”結合起來可以讓程式作出一些智能化的事情。

    然而,我們的程式還需要能很快地完成重複的事情。這節習題中我們將使用 for-loop (for 迴圈)來建立和列印出各種各樣的列表。在做的過程中,你會逐漸明白它們是怎麼回事。現在我不會告訴你,你需要自己找到答案。

    在你開始使用 for 迴圈之前,你需要在某個位置存放迴圈的結果。最好的方法是使用列表(list),顧名思義,它就是一個按順序存放東西的容器。列表並不複雜,你只是要學習一點新的文法。首先我們看看如何建立列表:

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

    你要做的是以 [ (左方括弧)開頭“開啟”列表,然後寫下你要放入列表的東西,用逗號隔開,就跟函數的參數一樣,最後你需要用 ] (右方括弧)結束右方括弧的定義。然後 Python 接收這個列表以及裡邊所有的內容,將其賦給一個變數。

Warning

    對於不會編程的人來說這是一個痛點。習慣性思維告訴你的大腦大地是平的。記得上一個練習中的 if 語句嵌套吧,你可能覺得要理解它有些難度,因為生活中一般人不會去像這樣的問題,但這樣的問題在編程中幾乎到處都是。你會看到一個函數調用另外一個包含 if 語句的函數,其中又有嵌套列表的列表。如果你看到這樣的東西一時無法弄懂,就用紙幣記下來,手動分割下去,直到弄懂為止。

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

 1 the_count = [1, 2, 3, 4, 5] 2 fruits = [‘apples‘, ‘oranges‘, ‘pears‘, ‘apricots‘] 3 change = [1, ‘pennies‘, 2, ‘dimes‘, 3, ‘quarters‘] 4  5 # this first kind of for-loop goes through a list 6 for number in the_count: 7     print "This is count %d" % number 8  9 # same as above10 for fruit in fruits:11     print "A fruit of type: %s" % fruit12 13 # also we can go through mixed lists too14 # notice we have to use %r since we don‘t know what‘s in it15 for i in change:16     print "I got %r" % i17 18 # we can also build lists, first start with an empty one19 elements = []20 21 # then use the range function to do 0 to 5 counts22 for i in range(0, 6):23     print "Adding %d to the list." % i24     # append is a function that lists understand25     elements.append(i)26 27 # now we can print them out too28 for i in elements:29     print "Element was: %d" % i
View Code你應該看到的結果

 

 

加分習題
  1. 注意一下 range 的用法。查一下 range 函數並理解它。
  2. 在第 22 行,你可以可以直接將 elements 賦值為 range(0,6),而無需使用 for 迴圈?
  3. 在 Python 文檔中找到關於列表的內容,仔細閱讀以下,除了 append 以外列表還支援哪些操作?

 

習題練習

 

笨辦法學Python(三十二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.