python笔记
列表
在python中,用方括号表示列表,元素之间用逗号分隔开。是个可变长序列,可以进行增删改操作。
定义一个列表
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
访问列表元素
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[0])
trek
注意列表的索引是从0开始的。python为访问最后一个元素提供了一种特殊的语法,可以使用索引为-1,同理,若想访问倒数第2个元素,索引为-2
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[-1])
specialized
添加、修改和删除元素
修改列表元素
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
bicycles[2] = 'train'
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
['trek', 'cannondale', 'train', 'specialized']
添加元素
在列表末尾添加元素用append函数
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
bicycles.append('ducati')
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
['trek', 'cannondale', 'redline', 'specialized', 'ducati']
在列表指定位置添加元素用insert函数
在调用函数时,不仅需要添加的元素,还有要添加的位置
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
bicycles.insert(0,'ducati')
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
['ducati', 'trek', 'cannondale', 'redline', 'specialized']
删除元素
使用del()语句删除元素
需要指明需要删除元素的位置,当把元素从列表中删除后,就再也无法使用它了。
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
del bicycles[-1]
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
['trek', 'cannondale', 'redline']
使用pop()删除函数
使用pop()可以删除列表中指定位置的元素,只需要在括号中指明删除元素的索引,另外可以访问被删除的值
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
bicycle = bicycles.pop(-1)
print(bicycle)
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
specialized
['trek', 'cannondale', 'redline']
根据值来删除元素
用remove()函数
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
bicycles.remove('redline')
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
['trek', 'cannondale', 'specialized']
组织列表
使用sort对列表进行排序
bicycles = ['trek','cannondale','redline','specialized']
bicycles.sort()
print(bicycles)
['cannondale', 'redline', 'specialized', 'trek']
可以看出使用sort()函数,将列表按照首字母顺序进行排序,并且是永久性的
bicycles.sort(reverse=True)
['trek', 'specialized', 'redline', 'cannondale']
也可以通过此种方法来按照字母顺序相反来排序,且为永久性更改
使用sorted临时排序
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
print(sorted(bicycles))
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
['cannondale', 'redline', 'specialized', 'trek']
['trek', 'cannondale', 'redline', 'specialized']
倒序打印列表
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
bicycles.reverse()
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
['specialized', 'redline', 'cannondale', 'trek']
是永久性的更改
列表长度
bicycles = ['trek','cannondale','redline','specialized']
print(len(bicycles))
4