方括号[]表示列表,列表内可放任意类别数据
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
下标 -1 代表最后一个,-2代表倒数第二个,以此类推
print(bicycles[-1]+'\n'+bicycles[-3])
specialized
cannondale
列表内容可以更改
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
append() 方法用于向列表尾添加元素
motorcycles.append("ducati")
print(motorcycles)
['ducati', 'yamaha', 'suzuki', 'ducati']
insert(idx,str) 方法可在列表任意位置添加新元素,idx代表新元素在列表中的位置
lost_list = ["key","note","pen"]
lost_list.insert(0,"laptop")
print(lost_list)
lost_list.insert(2,"mouse")
print(lost_list)
['laptop', 'key', 'note', 'pen']
['laptop', 'key', 'mouse', 'note', 'pen']
[]可以创建空列表
void_list = []
print(void_list)
[]
如果知道要删除的元素在列表中的位置,可使用del语句。
del motorcycles[0]
print(motorcycles)
['yamaha', 'suzuki', 'ducati']
方法pop()可删除列表末尾的元素并返回被删除元素的拷贝
poped_motorcycle = motorcycles.pop()
print(poped_motorcycle)
print(motorcycles)
ducati
['yamaha', 'suzuki']
pop() 也可删除任意位置处的元素
del_head = motorcycles.pop(0)
print(del_head)
print(motorcycles)
yamaha
['suzuki']
remove() 方法可实现根据内容删除元素,并不返回该元素
PS:仅删除列表中第一次出现过的
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
del_who = motorcycles.remove('yamaha')
print(motorcycles)
print(del_who)
['honda', 'suzuki', 'ducati']
None
sort() 直接在列表上进行排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
['audi', 'bmw', 'subaru', 'toyota']
也可以倒序
cars.sort(reverse=True)
print(cars)
['toyota', 'subaru', 'bmw', 'audi']
函数soted() 产生一个排序的副本,不对原列表进行更改
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars))
print(cars)
['audi', 'bmw', 'subaru', 'toyota']
['bmw', 'audi', 'toyota', 'subaru']
reverse() 方法可实现讲列表元素按照下标反转
cars.reverse()
print(cars)
['subaru', 'toyota', 'audi', 'bmw']
网友评论