python从入门到实践第三章——列表

'''
列表:列表名=[, , ,...]
'''
bicycle = ['trek','cannondale','redline']
print(bicycle)
'''
访问列表元素:列表名【索引号】
索引号从0开始而不是从1开始
返回最后一个列表元素:列表名[-1]
返回倒数第二个元素:列表名【-2】
主要用于不知道列表多长时使用
'''
bicycle = ['trek','cannondale','redline']
print(bicycle[0].title())
print(bicycle[-1])
'''
使用列表中的值
'''
bicycle = ['trek','cannonda','redline']
message = 'my first bicycle was a '+bicycle[1].title()+'.'
print(message)
'''
修改,添加和删除元素:
修改:列表名[索引] = 新元素
添加:将元素添加到列表末尾:.append()

'''
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
'''
创建一个空列表然后在其中添加yuansu
'''
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
'''
在列表中插入元素:
insert(索引,值)
'''
motorcycles = ['honda','yamaha','suzuki']
motorcycles.insert(0,'ducati')
print(motorcycles)
'''
从列表中删除元素:
del 列表名[索引号]
'''
motorcycles = ['honda','yamaha','suzuki']
del motorcycles[1]
print(motorcycles)
'''
.pop():将列表最后一个元素删除
.pop(索引号):将指定位置的元素删除
'''
motorcycles = ['honda','yamaha','suzuki']
popped_motorcycles = motorcycles.pop()
print(popped_motorcycles)
print(motorcycles)
motorcycles = ['honda','yamaha','suzuki']
print('the last motorcycle i own was a '+motorcycles.pop(1).title())
print(motorcycles)

'''
del 语句与.pop()的区别:
这个数据不在已任何方式使用它就用del。这个数据删除但还想再使用它用.pop()
'''
'''
不知道列表中元素所在的位置但是知道要删除什么值
.remove(元素)
'''
motorcycles = ['honda','yamaha','suzuki']
motorcycles.remove('honda')
print(motorcycles)

print(motorcycles.remove('honda'))这条语句输出为空

如果想要将.remove()的值保存继续使用需要事先将其保存在另一个变量里

motorcycles = ['honda','yamaha','suzuki']
too_expensive = 'honda'
motorcycles.remove('honda')
print(motorcycles)
print('\nA '+too_expensive+' is too expensive for me')
'''
排序:
.sort():永久性排序,且从小到大,顺序排列
.sort(reverse=true):反序排列
.sorted(列表名):临时排序:保留原来的顺序,同时按照特定的顺序排列
sorted(列表名,reverse= True):临时倒序排列。
'''
motorcycles = ['honda','yamaha','suzuki']
motorcycles.sort()
print(motorcycles)
print('--------')
motorcycles = ['honda','yamaha','suzuki']
motorcycles.sort(reverse=True)#注意大小写
print(motorcycles)
print('--------')
motorcycles = ['honda','yamaha','suzuki']
print('the original list is')
print(motorcycles)
print('the changed list is')
print(sorted(motorcycles))#临时排序
print('the original list is')
print(motorcycles)
'''
倒着打印:.reverse()
'''
print('--------')
motorcycles = ['honda','yamaha','suzuki']
motorcycles.reverse()
print(motorcycles)

确定列表长度len(列表)

print('--------')
motorcycles = ['honda','yamaha','suzuki']
print(len(motorcycles))

你可能感兴趣的:(python从入门到实践第三章——列表)