读书笔记 | Python学习之旅 Day13

Python学习之旅 读书笔记系列

Day 13

《Python编程从入门到实践》

复盘:第一部分基础知识(第1章~11章)

今天继续动手做练习题。

练习题

第四章 操作列表

继续第四章练习,主要针对切片和元组

1.pizzas_qiepian.py

在原有pizza程序上添加切片操作

pizzas = ["baconic","peperoni","ham","chicago","hotpie"]
for pizza in pizzas:
    print(pizza.title())
for pizza in pizzas:
    print("I like " + pizza.title() + " pizza!")
print("I really love " + pizza.title())

print("The first three items in the list are: ")
print(pizzas[0:3])
#[x,y]x为开始的索引(含),y为到达的索引(不含)
"""通过切片打印列表前三个元素"""
print("Three items from the middle of the list are: ")
print(pizzas[1:4])
"""通过切片打印列表中间三个元素"""
print("The last three items in the list are: ")
print(pizzas[2:5])
"""通过切片打印列表末尾三个元素"""

friend_pizzas = pizzas[0:4]
"""复制列表"""
pizzas.append("pisoln")
friend_pizzas.append("fpisoln")
print("My favorite pizzas are: ")
print(pizzas)
for pizza in pizzas:
    print("My favorite pizza are:" + pizza.title())
print("My friend's favorite pizzas are: ")
print(friend_pizzas)
for pizza in friend_pizzas:
    print("My friend's favorite pizza are: " + pizza.title())

输出结果如下:


day13_01.png

2.tuple_retur.py

元组为不能修改的列表,注意用:圆括号不是方括号标识

retur_foods = ("cake","rabbit","banana","apple","orange")
print("Resturant's foods have 5 type: ")
for food in retur_foods:
    print(food)
#retur_foods[0] = "leomen"
"""尝试修改元素"""
retur_foods = ("leomen","rabbit","banana","apple","watermelon")
"""修改元素变量,重新赋值"""
print("Resturant's foods have 5 type: ")
for food in retur_foods:
    print(food)

报错时如下:


day13_02.png

后续的输出结果如下:


day13_03.png
其他
  • 注意事项
    • 切片注意X值包含,Y值不包含
    • 赋值列表通过切片时要复制,不能直接等于

你可能感兴趣的:(读书笔记 | Python学习之旅 Day13)