首页 > 编程 > Python > 正文

Python -- 2. 列表

2019-11-08 01:35:20
字体:
来源:转载
供稿:网友

1. 列表是什么 由一系列按特定顺序排列的元素组成,在Python中,用方括号([] )来表示列表,并用逗号来分隔其中的元素。

bicycles = ['trek', 'cannondale', 'redline', 'specialized']PRint(bicycles)

(1). 访问列表元素 要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可,索引从0而不是1开始。

bicycles = ['trek', 'cannondale', 'redline', 'specialized']print(bicycles[0])

(2). 访问最后一个列表元素,通过将索引指定为-1

bicycles = ['trek', 'cannondale', 'redline', 'specialized']print(bicycles[-1])

2. 修改、添加和删除元素 (1). 修改列表元素

motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)motorcycles[0] = 'ducati'print(motorcycles)

(2). 在列表中添加元素 在列表末尾添加元素,append()

motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)motorcycles.append('ducati')print(motorcycles)

在任何位置插入元素,insert(n) 方法insert() 在索引n 处添加空间,并将值存储到这个地方。这种操作将列表中既有的每个元素都右移一个位置.

(3). 从列表中删除元素 使用del 可删除任何位置处的列表元素

motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)del motorcycles[0]print(motorcycles)

使用方法pop() 删除列表末尾元素

motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)popped_motorcycle = motorcycles.pop()print(motorcycles)print(popped_motorcycle)

弹出列表中任何位置处的元素,pop(n)

motorcycles = ['honda', 'yamaha', 'suzuki']first_owned = motorcycles.pop(0)print('The first motorcycle I owned was a ' + first_owned.title() + '.')

如果你不确定该使用del 语句还是pop() 方法,下面是一个简单的判断标准:如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del 语句;如果你要在删除元素后还能继续使用它,就使用方法pop()

根据值, 删除元素,remove()

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']print(motorcycles)motorcycles.remove('ducati')print(motorcycles)

使用remove() 从列表中删除元素时,也可接着使用它的值。 注意 方法remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断.



3. 组织列表 (1). 使用方法sort() 对列表进行永久性排序

cars = ['bmw', 'audi', 'toyota', 'subaru']cars.sort()print(cars)

(2). 反向排序,只需向sort() 方法传递参数reverse=True 。

cars = ['bmw', 'audi', 'toyota', 'subaru']cars.sort(reverse=True)print(cars)

(3). 使用函数sorted() 对列表进行临时排序

cars = ['bmw', 'audi', 'toyota', 'subaru']print("Here is the original list:")print(cars)print("/nHere is the sorted list:")print(sorted(cars))print("/nHere is the original list again:")print(cars)

(4). 反转列表,reverse() 要反转列表元素的排列顺序,可使用方法reverse()

cars = ['bmw', 'audi', 'toyota', 'subaru']print(cars)cars.reverse()print(cars)

方法reverse() 永久性地修改列表元素的排列顺序

4. 确定列表的长度 使用函数len() 可快速获悉列表的长度

>>> cars = ['bmw', 'audi', 'toyota', 'subaru']>>> len(cars)4
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表