高級編程技術(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 + / 可以將某一代碼段同時寫爲註釋,再次使用就可以同時取消註釋。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章