您的位置:首页 > 编程语言 > Python开发

Python编程:从入门到实践-笔记 《列表》

2017-12-19 20:13 741 查看
#列表的常用操作方法

#-->修改列表的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)

#-->在列表中添加元素

#--> 1.在列表末尾添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)

#-->在列表中插入元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0,'ducati')
print(motorcycles)

#-->在列表中删除元素

#--> 1.使用del语句删除元素(知道要删除的元素索引位置)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

del motorcycles[0]
print(motorcycles)

#--> 2.使用pop()方法删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)

#--> 3.也可以使用pop()方法删除指定位置的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

popped_motorcycle = motorcycles.pop(1)
print(motorcycles)
print(popped_motorcycle)

#--> 4.使用remove()方法删除元素(根据值删除元素)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

motorcycles.remove('honda')
print(motorcycles)

#--> 5.使用sort()方法对列表进行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
#    通过向sort()方法传递参数reverse=True,对列表反向排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)

#--> 6.使用函数sorted()对列表进行临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars))
print(cars)#列表原顺序不变
#tips:
#如果通过赋值的方式复制列表,如果改变源列表则引用
# 列表也会随之改变
l1 = ['a','b','c']
l2 = l1
l1.append('d')
print(l1)
print(l2)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐