使用列表的各个值
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)
组织列表
用sort() 按字母排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
反向排序:向sort()方法传递参数reverse=True
cars = ['bmw', 'audi', 'toyota','subaru']cars.sort(reverse=True)
用sorted()临时排序(另外,sorted()也可以传递参数reverse=True)
print(sorted(cars))
倒着打印列表:reverse()
cars.reverse()
print(cars)
确定列表长度
>>> len(cars)
4