python打卡第3天:操作列表☁
操作列表
- 遍历列表:for循环
示例:
#想出至少三种有共同特征的动物
#将这些动物的名称储存在一个列表中
#再用for循环将每种动物的名称都打出来
#修改这个代码,使其针对每种动物都打印一个句子
#在程序末尾添加一行代码,指出这些动物的共同之处
aninmals=["dog","cat","pig"]
for aninmal in aninmals:
print(aninmal) #将每种动物的名称都打出来
print("A "+aninmal+" would be a great pet!"+"\n")
print("Any of the aninmals would make a great pet!")
3. 创建数字列表:使用函数range()
示例
#创建一个偶数列表
#列表数字从2到10
even_numbers=list(range(2,11,2)) #range(2,11,2)生成一个起始值为2,终止值为11-1=10,步长为2的数字,list()将生成的数字转换为列表
print(even_numbers)
5. 使用列表的一部分:列表切片
my_foods=['pizza','falafel','carrot cake']
friends_food=my_foods[:2] #提取my_foods列表中的从第零个到第一个元素
my_foods.append("cannli")
friends_food.append("ice cream")
print("My favorite foods are: ")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friends_food)
7. 元组:列表元素可修改,但元组元素不可修改,只能整个替换。
参考文献:Python编程:从入门到实践/(美)Eric Matths 著