1. 程式人生 > >高階程式設計技術(Python)作業4

高階程式設計技術(Python)作業4

4-9 立方解析:使用列表解析生成一個列表,其中包含前10個整數的立方。

Solution:

cubes = [num ** 3 for num in range(1, 11)]
for cube in cubes:
    print(cube, end = " ")

Output:

1 8 27 64 125 216 343 512 729 1000 

注:使用end = “字元” 可以設定print的末尾,避免每一個元素都換行。

4-10 切片:選擇你在本章編寫的一個程式,在末尾新增幾行程式碼,以完成如下任務。
- 列印訊息“The first three items in the list are:”,再使用切片來列印列表的前三個元素。
- 列印訊息“Three items from the middle of the list are:”,再使用切片來列印列表中間的三個元素。
- 列印訊息“The last three items in the list are:”,再使用切片來列印列表末尾的三個元素。

Solution:

cubes = [num ** 3 for num in range(1, 11)]
for cube in cubes:
    print(cube, end = " ")
print("\nThe first three items in the list are " + str(cubes[:3]))
print("Three items from the middle of the list are " + str(cubes[5:8]))
print("The last three items in the list are " + str(cubes[-3
:]))

Output:

1 8 27 64 125 216 343 512 729 1000 
The first three items in the list are [1, 8, 27]
Three items from the middle of the list are [216, 343, 512]
The last three items in the list are [512, 729, 1000]

注:對列表使用str強制型別轉換會將中括號保留下來。

4-11 你的比薩和我的比薩:在你為完成練習4-1而編寫的程式中,建立比薩列表的副本,並將其儲存到變數friend_pizzas 中,再完成如下任務。
- 在原來的比薩列表中新增一種比薩。
- 在列表friend_pizzas 中新增另一種比薩。
- 核實你有兩個不同的列表。為此,列印訊息“My favorite pizzas are:”,再使用一個for 迴圈來列印第一個列表;列印訊息“My friend’s favorite pizzas are:”,再使用一 個for 迴圈來列印第二個列表。核實新增的比薩被新增到了正確的列表中。

Solution:

pizzas = ["pepperoni", "mushroom", "hawaii"]
for pizza in pizzas:
    print("I like " + pizza + " pizza.")

print("\n" + pizzas[0].title() + " pizza is hot.")
print(pizzas[1].title() + " pizza is my favourite.")
print(pizzas[2].title() + " pizza is my dinner last night.")
print("I really love pizza!")

friend_pizzas = pizzas[:]
pizzas.append("salmon")
friend_pizzas.append("seafood")

print("\nMy favourite pizzas are", end = " ")
for pizza in pizzas[:2]:
    print(pizza + " pizza", end = ", ")
print(pizzas[-2]+ " pizza and " + pizzas[-1] + " pizza.")

print("\nMy friend's favourite pizzas are", end = " ")
for friend_pizza in friend_pizzas[:2]:
    print(friend_pizza + " pizza", end = ", ")
print(friend_pizzas[-2]+ " pizza and " + friend_pizzas[-1] + " pizza.")

Output:

I like pepperoni pizza.
I like mushroom pizza.
I like hawaii pizza.

Pepperoni pizza is hot.
Mushroom pizza is my favourite.
Hawaii pizza is my dinner last night.
I really love pizza!

My favourite pizzas are pepperoni pizza, mushroom pizza, hawaii pizza and salmon pizza.

My friend's favourite pizzas are pepperoni pizza, mushroom pizza, hawaii pizza and seafood pizza.

注:直接使用單純的迴圈輸出不符合英文的習慣說法,所以我對字串進行了一些比較複雜的操作,讓語句顯得自然一點。

最後關於書中附錄B中sublime的快捷鍵的使用:
- Ctrl + ] 可以將某一程式碼段同時縮排。
- Ctrl + [ 可以將某一程式碼段同時取消縮排。
- Ctrl + / 可以將某一程式碼段同時寫為註釋,再次使用就可以同時取消註釋。