列表简介
在python中用[ ]
表示列表,并用逗号来分隔其中元素。
给列表指定一个复数名称(letters,names,and so on)是个不错的注意。
访问列表元素
1 2 3 4 5 6 7 8 9 10 11 12
| bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles) print(bicycles[0]) print(bicycles[-1]) print(bicycles[-2]) print('my bicycle is ' + bicycles[2].title()) ---------------------------------------------------- ['trek', 'cannondale', 'redline', 'specialized'] trek specialized redline my bicycle is Redline
|
- 索引从0开始,而非1;
- 列表中的元素被提取出来就是一个具体的数据类型,比如字符串、数字等,可以被使用。
修改、添加和删除元素
修改元素
1 2 3 4
| bicycles[-1] = 'tata' print(bicycles) ---------------------------- ['trek', 'cannondale', 'redline', 'tata']
|
添加元素
1 2 3 4 5 6 7 8 9 10 11
| bicycles.append('fhuang') print(bicycles)
bicycles.insert(0,'cona') print(bicycles)
---------------------------- ['trek', 'cannondale', 'redline', 'tata', 'fhuang'] ['cona', 'trek', 'cannondale', 'redline', 'tata', 'fhuang']
|
删除元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| print(bicycles)
del bicycles[-1] print(bicycles)
popped_bicycle = bicycles.pop(0) print(popped_bicycle) print(bicycles)
remove_bicycle = 'tata' bicycles.remove(remove_bicycle) print(remove_bicycle) print(bicycles)
------------------------------------ ['cona', 'trek', 'cannondale', 'redline', 'tata', 'fhuang'] ['cona', 'trek', 'cannondale', 'redline', 'tata'] cona ['trek', 'cannondale', 'redline', 'tata'] tata ['trek', 'cannondale', 'redline']
|
组织列表(元素排序)
永久排序
1 2 3 4 5 6 7 8 9 10 11 12 13
| print(bicycles)
bicycles.sort() print(bicycles)
bicycles.sort(reverse=True) print(bicycles) ---------------------------------------- ['trek', 'cannondale', 'redline'] ['cannondale', 'redline', 'trek'] ['trek', 'redline', 'cannondale']
|
临时排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| print(bicycles)
print(sorted(bicycles)) print(bicycles)
print(sorted(bicycles,reverse=True)) print(bicycles) ---------------------------------------- ['trek', 'redline', 'cannondale'] ['cannondale', 'redline', 'trek'] ['trek', 'redline', 'cannondale'] ['trek', 'redline', 'cannondale'] ['trek', 'redline', 'cannondale']
|
反转列表
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| print(bicycles)
bicycles.reverse() print(bicycles)
bicycles.reverse() print(bicycles) -------------------------------------------------- ['trek', 'redline', 'cannondale'] ['cannondale', 'redline', 'trek'] ['trek', 'redline', 'cannondale']
|
确定列表长度
1 2 3 4 5 6 7
| print(bicycles)
print(len(bicycles)) -------------------------------------- ['trek', 'redline', 'cannondale'] 3
|