Python (三)
列表
在Python中,用方括号[] 表示列表,并用逗号分隔其中的元素
初识列表:
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
输出结果:
['trek', 'cannondale', 'redline', 'specialized']
1.访问列表元素
print(bicycles[0])
输出结果:
trek
注意:在Python中,第一个列表元素的索引为0,而不是1.
访问最后一个元素
print(bicycles[-1])
输出结果:
specialized
2.修改、添加和删除元素
2.1修改列表元素
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
输出结果:
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
可以修改任意列表元素的值,而不仅仅是第一个元素的值
2.2 在列表中添加元素
2.2.1在列表末尾添加元素
motorcycles.append('ducati')
用append()方法将元素‘ducati‘添加到列表末尾
输出结果:
['honda', 'yamaha', 'suzuki', 'ducati']
2.2.2在列表中插入元素
使用insert()可在列表的任何位置添加新元素
motorcycles.insert(0,'ducati')
输出结果:
['ducati', 'honda', 'yamaha', 'suzuki']
2.3 在列表中删除元素
2.3.1使用del语句删除元素
del motorcycles[0]
输出结果:
[‘honda’, ‘yamaha’, ‘suzuki’]
[‘yamaha’, ‘suzuki’]
使用del可删除任意位置处的列表元素,条件是知道其索引
2.3.2 使用方法pop()删除元素
方法pop()删除列表末尾的元素,并让你能够接着使用它
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
poped_motorcycles = motorcycles.pop()
print(motorcycles)
print(poped_motorcycles)
输出结果:
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
2.4弹出列表中任何位置处的元素
first_owned = motorcycles.pop(0) #删除第一个元素并把值赋给此变量
print(f"The first motorcycle I owned was a {first_owned.title()}")
输出结果:
The first motorcycle I owned was a Honda
2.5 根据值删除元素
motorcycles = ['honda','yamaha','suzuki','ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
输出结果:
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
3.组织列表
3.1使用方法sort()对列表永久排序
方法sort()永久性地修改列表元素的排列顺序
cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
输出结果:
['audi', 'bmw', 'subaru', 'toyota']
还可以按与字母顺序相反的顺序排列列表元素,只需向sort()方法传递参数 reverse = True
cars = ['bmw','audi','toyota','subaru']
cars.sort(reverse=True)
print(cars)
输出结果:
['toyota', 'subaru', 'bmw', 'audi']
3.2 使用函数sorted()对列表临时排序
函数sorted()让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序
print("Here is the original list:")
print(cars)
print("\nHere is the original list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
输出结果:
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the original list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']
3.3倒着打印列表
使用方法reverse(),可永久性地修改列表元素的排列顺序,如想恢复,只需再次调用
cars = ['bmw','audi','toyota','subaru']
print(cars)
cars.reverse();
print(cars)
输出结果:
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
3.4确定列表的长度
cars = ['bmw','audi','toyota','subaru']
print(len(cars))
输出结果:
4