欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

習(xí)題 32: 循環(huán)和列表?

現(xiàn)在你應(yīng)該有能力寫更有趣的程序出來了。如果你能一直跟得上,你應(yīng)該已經(jīng)看出將“if 語句”和“布爾表達(dá)式”結(jié)合起來可以讓程序作出一些智能化的事情。

然而,我們的程序還需要能很快地完成重復(fù)的事情。這節(jié)習(xí)題中我們將使用 for-loop (for 循環(huán))來創(chuàng)建和打印出各種各樣的列表。在做的過程中,你會(huì)逐漸明白它們是怎么回事。現(xiàn)在我不會(huì)告訴你,你需要自己找到答案。

在你開始使用 for 循環(huán)之前,你需要在某個(gè)位置存放循環(huán)的結(jié)果。最好的方法是使用列表(list),顧名思義,它就是一個(gè)按順序存放東西的容器。列表并不復(fù)雜,你只是要學(xué)習(xí)一點(diǎn)新的語法。首先我們看看如何創(chuàng)建列表:

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

你要做的是以 [ (左方括號(hào))開頭“打開”列表,然后寫下你要放入列表的東西,用逗號(hào)隔開,就跟函數(shù)的參數(shù)一樣,最后你需要用 ] (右方括號(hào))結(jié)束右方括號(hào)的定義。然后 Python 接收這個(gè)列表以及里邊所有的內(nèi)容,將其賦給一個(gè)變量。

Warning

對(duì)于不會(huì)編程的人來說這是一個(gè)難點(diǎn)。習(xí)慣性思維告訴你的大腦大地是平的。記得上一個(gè)練習(xí)中的 if 語句嵌套吧,你可能覺得要理解它有些難度,因?yàn)樯钪幸话闳瞬粫?huì)去像這樣的問題,但這樣的問題在編程中幾乎到處都是。你會(huì)看到一個(gè)函數(shù)調(diào)用另外一個(gè)包含 if 語句的函數(shù),其中又有嵌套列表的列表。如果你看到這樣的東西一時(shí)無法弄懂,就用紙筆記下來,手動(dòng)分割下去,直到弄懂為止。

現(xiàn)在我們將使用循環(huán)創(chuàng)建一些列表,然后將它們打印出來。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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 number in the_count:
    print "This is count %d" % number

# same as above
for fruit in fruits:
    print "A fruit of type: %s" % fruit

# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
    print "I got %r" % i

# we can also build lists, first start with an empty one
elements = []

# then use the range function to do 0 to 5 counts
for i in range(0, 6):
    print "Adding %d to the list." % i
    # append is a function that lists understand
    elements.append(i)

# now we can print them out too
for i in elements:
    print "Element was: %d" % i

你應(yīng)該看到的結(jié)果?

$ python ex32.py
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
$

加分習(xí)題?

  1. 注意一下 range 的用法。查一下 range 函數(shù)并理解它。
  2. 在第 22 行,你可以可以直接將 elements 賦值為 range(0,6),而無需使用 for 循環(huán)?
  3. 在 Python 文檔中找到關(guān)于列表的內(nèi)容,仔細(xì)閱讀以下,除了 append 以外列表還支持哪些操作?

Project Versions

Table Of Contents

Previous topic

習(xí)題 31: 作出決定

Next topic

習(xí)題 33: While 循環(huán)

This Page