- 列表是Python中最通用的对象类型之一,是对象的有序集合。它由方括号括起来并且里面的元素通过逗号分隔。
创建一个列表
first_list=[1,2,3,4,5]
other_list=[1,'two',3,4,'last']
- 一个列表也可以包含另一个列表
nested_list=[1,'two',first_list,4,'last']
nested_list
[1, 'two', [1, 2, 3, 4, 5], 4, 'last']
- 创建空列表
空列表没有任何用处,但有时我们可能会先定义一个空列表然后再添加元素。
empty_list=[]
1 访问列表元素
与其它数据类型一样,可以通过从0开始的索引获得列表元素。
first_list[0]
1
first_list[1]
2
负数用于从右边访问列表
first_list[-1]
5
获取列表的另一种方法是通过使用内置函数list()将非列表对象转换为列表
aseq='atggctaggc'
list(aseq)
['a', 't', 'g', 'g', 'c', 't', 'a', 'g', 'g', 'c']
2. 多个重复项目的列表
如果要初始化具有重复多次的相同项的列表,可以像这样使用 * 操作符
sample=['red']*5
sample
['red', 'red', 'red', 'red', 'red']
可以用空值预先填充列表,在处理大列表并且预先知道元素数量时非常有用。定义一个固定大小的列表比创建一个空列表并根据需要展开它更有效。
sample=['None']*5
sample
['None', 'None', 'None', 'None', 'None']
3. 列表推导式
任何Python函数或方法都可以通过推导式来定义列表。
a=[0,1,2,3,4,5]
[3*x for x in a]
[0, 3, 6, 9, 12, 15]
用相同的元素做一个列表,但是没有前后空格
animals = [' King Kong',' Godzilla ',' Gamera ']
[x.strip() for x in animals]
['King Kong', 'Godzilla', 'Gamera']
我们可以添加条件语句(if)来缩小结果集
[x.strip() for x in animals if 'i' in x]
['King Kong', 'Godzilla']
4. 修改列表
与字符串不同,列表可以通过添加、删除或更改元素。
添加元素
有三种向列表中添加元素的方法:append,insert以及extend。
- append(element):在列表末尾添加一个元素。
first_list.append(99)
first_list
[1, 2, 3, 4, 5, 99]
- insert(position,element):在特定位置插入元素
first_list.insert(2,50)
first_list
[1, 2, 50, 3, 4, 5, 99]
- extend(list):通过在原始列表的末尾添加列表来扩展列表。
first_list.extend([6,7,8])
first_list
[1, 2, 50, 3, 4, 5, 99, 6, 7, 8]
删除元素
从列表中删除元素有三种方法:pop,remove以及del。
- pop(index):移除索引位置中的元素并将其返回到调用它的位置。如果没有参数,则返回最后一个元素。
first_list.pop()
first_list.pop(2)
first_list
[1, 2, 3, 4, 5, 99, 6, 7]
- remove(element):移除参数中指定的元素。如果列表中有同一对象的多个副本,则从左侧开始计数,删除第一个副本。与pop()不同,这个函数不返回任何东西。
first_list.remove(99)
first_list
[1, 2, 3, 4, 5, 6, 7]
- del
del first_list[0]
first_list
[2, 3, 4, 5, 6, 7]
5. 复制列表
在下面的代码中,我们尝试将列表a复制到b中,但是当我通过删除一个元素来修改b时,这个元素也从a中删除了:
a=[1,2,3]
b=a
b.pop()
a
[1, 2]
" = "并不复制值,而是复制对原始对象的引用。要复制一个列表,你必须使用copy模块中的copy方法或者[:]
import copy
a=[1,2,3]
b=copy.copy(a)
b.pop()
a
[1, 2, 3]
#[:]
b=a[:]
b.pop()
a
[1, 2, 3]