python从入门到实践之第3章 列表简介
作者:互联网
使用列表的各个值
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
修改列表元素
例如修改第一个honda
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
在列表中插入元素
例如在第一个元素前面再插入一个元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0,'ducati')
print(motorcycles)
从列表中删除元素
利用del语句
例如删除第一个
del motorcycles[0]
print(motorcycles)
利用pop()删除列表末尾的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
输出为
[‘honda’, ‘yamaha’, ‘suzuki’]
[‘honda’, ‘yamaha’]
suzuki
即删除元素储存在变量popped_motorcycle中了
也可以用pop删除任何位置的元素
例如删除第一个
first_owned = motorcycles.pop(0)
根据值删除
motorcycles.remove('ducati')print(motorcycles)
标签:元素,入门,yamaha,python,简介,honda,print,suzuki,motorcycles 来源: https://blog.csdn.net/weixin_44770248/article/details/89110442