《笨方法學Python》加分題32

注意一下 range 的用法。查一下 range 函數並理解它
在第 22 行(個人答案),你能夠直接將 elements 賦值爲 range(0, 6) ,而無需使用 for 循環?
在 python 文檔中找到關於列表的內容,仔細閱讀一下,除了 append 之外列表還支持哪些操做?

python

個人答案

32.0 基礎練習

 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 
 7 for number in the_count:
 8     print(f"This is count {number}")
 9 
10 # same as above
11 
12 for fruit in fruits:
13     print(f"A fruit of type: {fruit}")
14 
15 # also we can go through mixed lists too
16 # notice we have to use {} since we don't know what's in it
17 
18 for i in change:
19     print(f"I got {i}")
20 
21 # we can also build lists, first start with an empty one
22 elements = []
23 
24 #then use the range function to do 0 to 5 counts
25 
26 for i in range(0,6):
27     print(f"Adding {i} to the list.")
28     # append is a function that lists understand
29     elements.append(i)
30 
31 # now we can print them out too
32 for i in elements:
33     print(f"Element was: {i}")
34 
35 #本身加的,看elements結果
36 print(elements)

 

 

32.1 range 的用法

最簡單的變法就是查看幫助文檔了,還記得咱們用過的兩種方法麼? 
( ↓↓↓↓ 刮開查看 ↓↓↓↓ ) app

Python3 range() 函數返回的是一個可迭代對象(類型是對象),而不是列表類型, 因此打印的時候不會打印列表。函數

Python3 list() 函數是對象迭代器,能夠把range()返回的可迭代對象轉爲一個列表,返回的變量類型爲列表。oop

 

range(stop) range(start, stop[, step])


建立 range 函數的實例 
range 函數會返回一個數字序列。它最多接受 3 個參數ui

      • start:啓始值(被包含),默認是 0
      • stop:結束值(不包含),必填
      • step:步長,默認是1,不可爲0,例如:range(0, 5) 等價於 range(0, 5, 1)
 1 >>>range(5)
 2 range(0, 5)
 3 >>> for i in range(5):
 4 ...     print(i)
 5 ... 
 6 0
 7 1
 8 2
 9 3
10 4
11 >>> list(range(5))
12 [0, 1, 2, 3, 4]
13 >>> list(range(0))
14 []
15 >>>

有兩個參數或三個參數的狀況(第二種構造方法)::this

 
 1 >>>list(range(0, 30, 5))
 2 [0, 5, 10, 15, 20, 25]
 3 >>> list(range(0, 10, 2))
 4 [0, 2, 4, 6, 8]
 5 >>> list(range(0, -10, -1))
 6 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
 7 >>> list(range(1, 0))
 8 []
 9 >>>
10 >>>

 

 

32.2 不使用 for-loop ,直接爲 elements 賦值爲 range(6)

 

 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 
 7 for number in the_count:
 8     print(f"This is count {number}")
 9 
10 # same as above
11 
12 for fruit in fruits:
13     print(f"A fruit of type: {fruit}")
14 
15 # also we can go through mixed lists too
16 # notice we have to use {} since we don't know what's in it
17 
18 for i in change:
19     print(f"I got {i}")
20 
21 # we can also build lists, first start with an empty one
22 elements = []
23 
24 #then use the range function to do 0 to 5 counts
25 
26 elements = list(range(0,6))
27 
28 # now we can print them out too
29 for i in elements:
30     print(f"Element was: {i}")
31 
32 #本身加的,看elements結果
33 print(elements)

 

須要爲range(0,6)加上list纔是須要的elements列表spa