列表:列表由一系列按特定顺序排列的元素组成
1.由 [] 表示
list = ['trek','cannondale','redline','specialized']
print(list)
输出:['trek', 'cannondale', 'redline', 'specialized']
2.访问列表的第一个元素,索引从 0 开始
print(list[0])
输出:trek
3. 输出首字母大写
print(list[0].title())
输出:Trek
4.修改列表元素
list[0] = 'ducati'
输出:['ducati', 'cannondale', 'redline', 'specialized']
5.在末尾添加元素
list.append('ducati')
输出:['ducati', 'cannondale', 'redline', 'specialized', 'ducati']
6.在列表中插入元素
list.insert(0,'ducati')
输出:['ducati', 'ducati', 'cannondale', 'redline', 'specialized', 'ducati']
7.del 语句删除元素
del list[0]
输出:['ducati', 'cannondale', 'redline', 'specialized', 'ducati']
8.pop语句删除元素
list = ['trek','cannondale','redline','specialized']
list.pop()
list.pop(1)
print(list)
输出:['trek', 'cannondale', 'redline']
输出:['trek', 'redline', 'specialized']
9.remove语句删除元素
list = ['trek','cannondale','redline','specialized']
list.remove('trek')
print(list)
输出:['cannondale', 'redline', 'specialized']
10. sort()方法对列表进行永久排序
list.sort(reverse=True) 按照相反的方向进行排序
list = ['trek','cannondale','redline','specialized']
list.sort()
print(list)
输出:['cannondale', 'redline', 'specialized', 'trek']
11. sorted()对列表临时排序
list = ['trek','cannondale','redline','specialized']
print(list)
list = ['trek','cannondale','redline','specialized']
print(sorted(list))
list = ['trek','cannondale','redline','specialized']
print(list)
输出:
['trek', 'cannondale', 'redline', 'specialized']
['cannondale', 'redline', 'specialized', 'trek']
['trek', 'cannondale', 'redline', 'specialized']
12.倒着打印列表
list = ['trek','cannondale','redline','specialized']
list.reverse()
print (list)
输出:
['specialized', 'redline', 'cannondale', 'trek']
13.确定列表的长度
list = ['trek','cannondale','redline','specialized']
print(len(list))
输出:
4