目录
序列介绍
- (13种基本序列类型:list、tuple、range(数字序列对象)
- (2)专门处理文本的附加序列类型:str
- (3)专门处理二进制数据的附加序列类型: bytes、bytearray、memoryview
一、列表介绍
- 列表是可变序列,通常用于存放同类项目的集合,可以用多种方式构建列表:
- 使用一对方括号来表示空列表: []
- 使用方括号,其中的项以逗号分隔: [a], [a, b, c]
- 使用列表推导式: [x for x in iterable]
- 使用类型的构造器: list() 或 list(iterable)
- 注:iterable 可以是序列、支持迭代的容器或其它可迭代对象。
二、列表增删改查
1.访问列表
s[i] s 的第 i 项,起始为 0
s[i:j] s 从 i 到 j 的切片
s[i:j:k] s 从 i 到 j 步长为 k 的切片
例:
list= [1, 2, 3, 4, 5, 6, 7 ];
(1)list[0] :返回第列表第1位
(2)list[1:5]:返回第2至第5位数据
(3)list[1:]:返回第2位至最后一位数据
(4)list[:6]:返回第1位至第7位数据
(5)list[:]:返回所有数据
(6)list[:-3]:返回第1位至倒数第4位数据(注:不包括倒数第3位数据)
2.修改列表
list = ['Google', 'Runoob', 1997, 2000]
list[2] = 2001
#结果:['Google', 'Runoob', 2001, 2000]
3.增加列表元素
参考list.append() 与 list.insert() 方法
4.删除列表元素
(1)参考list.pop() 与 list.remove() 方法
(2)del语句
例:
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0]
del a[2:4]
5.删除列表
del list
6.清空列表
(1)list.clear()
(2)del lst[:]
三、列表拼接与扩展
注:第1、3点实现扩展,即在原列表增加元素;第2点实现拼接并生成新列表
- 1.参考 list.extend() 方法
- 2.用+号: list3=list1+list2
- 3.用+=号: lst1+=list2
四、列表函数
len(list) 列表元素个数
max(list) 返回列表元素最大值
min(list) 返回列表元素最小值
list(seq) 将元组转换为列表
五、列表方法
通用操作方法:
- x in s 如果 s 中的某项等于 x 则结果为 True,否则为 False
- x not in s 如果 s 中的某项等于 x 则结果为 False,否则为 True
- s + t s 与 t 相拼接
- s * n 或 n * s 相当于 s 与自身进行 n 次拼接
- s[i] s 的第 i 项,起始为 0
- s[i:j] s 从 i 到 j 的切片
- s[i:j:k] s 从 i 到 j 步长为 k 的切片
- len(s) s 的长度
- min(s) s 的最小项
- max(s) s 的最大项
- s.index(x[, i[, j]]) x 在 s 中首次出现项的索引号(索引号在 i 或其后且在 j 之前)
- s.count(x) x 在 s 中出现的总次数
列表操作方法:
- list.append() 在列表末尾添加新的对象
- list.count() 统计某个元素在列表中出现的次数
- list.extend() 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
- list.index() 从列表中找出某个值第一个匹配项的索引位置,0表示第1位
- list.insert() 将对象插入列表的指定索引位置
- list.pop() 按索引移除列表中的一个元素,并且返回该元素的值,若不指定索引则默认最后一个元素
- list.remove() 移除列表中某个值的第一个匹配项
- list.reverse() 反向列表中元素
- list.sort() 对原列表进行排序
- list.clear() 清空列表
- list.copy() 复制列表
1.list.append(obj)
在列表末尾添加新的对象
例:
lst1=['a','b']
lst1.append('c') #结果:['a','b','c']
2.list.count(obj)
统计某个元素在列表中出现的次数
例:
aList = [123, 'Google', 'Runoob', 'Taobao', 123]
print ("123 元素个数 : ", aList.count(123))
3.list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
seq -- 元素列表,可以是列表、元组、集合、字典,若为字典,则仅会将键(key)作为元素依次添加至原列表的末尾
例:
list1 = ['Google', 'Runoob', 'Taobao']
list2=list(range(5)) # 创建 0-4 的列表
list1.extend(list2) # 扩展列表
print ("扩展后的列表:", list1)
#扩展后的列表: ['Google', 'Runoob', 'Taobao', 0, 1, 2, 3, 4]
4.list.index(obj)
从列表中找出某个值第一个匹配项的索引位置,0表示第1位,
注:若没有找到则会抛出异常
例:
list1 = ['Google', 'Runoob', 'Taobao']
print ('Runoob 索引值为', list1.index('Runoob'))
#Runoob 索引值为 1
5.list.insert(index, obj)
将对象插入列表
index -- 对象obj需要插入的索引位置
obj -- 要插入列表中的对象
例;
list1 = ['Google', 'Runoob', 'Taobao']
list1.insert(1, 'Baidu')
print ('列表插入元素后为 : ', list1)
#列表插入元素后为 : ['Google', 'Baidu', 'Runoob', 'Taobao']
6.list.pop([index=-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
index -- 可选参数,要移除列表元素的索引值,不能超过列表总长度,默认为 index=-1,删除最后一个列表值
例:
list1=['a','b','c','d','e']
pop_ret=list1.pop(1)
#结果:pop_ret为'b',list1为['a', 'c', 'd', 'e']
pop_ret=list1.pop()
#结果:pop_ret为'e',list1为['a', 'c', 'd']
7.list.remove(obj)
移除列表中某个值的第一个匹配项
例:
list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.remove('Taobao')
8.list.reverse()
反向列表中元素
例:
list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.reverse()
#结果:['Baidu', 'Taobao', 'Runoob', 'Google']
9.list.sort( key=None, reverse=False)
对原列表进行排序
key :主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse :排序规则,reverse = True 降序, reverse = False 升序(默认)。
例1:
lst1 = ['123', 'xyz', 'zara', 'abc', 'xyz']
lst1.sort(reverse = True)
例2:
li=[1,2,3,4,5]
l1=[1,5,3,2]
l1.sort(key=li.index)
print(l1)
#结果:[1, 2, 3, 5]
例3:
file_list.sort(key=lambda file: os.path.getmtime(path + '/' + file))
10.list.clear()
清空列表
例:
list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.clear()
11.list.copy()
复制列表
例:
list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list2 = list1.copy()
12.join list
list1=('len','speak','chinese')
res_str='_'.join(list1)
#结果:'len_speak_chinese'
六、列表推导式
1.常用列表推导式
[expression for iter_val in iterable]
[expression for iter_val in iterable if cond_expr]
例:
list1=[y for y in range(1910,1920) ];
leaps=[y for y in range(1910,1940) if (y%4==0) and (y%100!=0)];
2.嵌套推导式
(1)单层嵌套
例1:
combs=[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
等价于:
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x, y))
例2:
a_list=[j for i in range(2,8) if i>4 for j in range(i*2,50,i) if j>40]
等价于
b=[]
for i in range(2,8):
if i>4:
for j in range(i*2,50,i):
if j>40:
b.append(j)
(2)多层嵌套
a=[j for k in range(1,5) for i in range(2,8) if i>4 for j in range(i*2,50,i) if j>40]
等价于
b=[]
for k in range(1,5):
for i in range(2,8):
if i>4:
for j in range(i*2,50,i):
if j>40:
b.append(j)
七、列表常用操作
1.列表去重
(1)利用set
缺点是无法保证去重后的顺序
li=[1,2,3,4,5,1,2,3]
li=list(set(li))
(2)利用set+索引,保证去重后的顺序不变
li=[1,2,3,4,5,1,2,3]
new_li=list(set(li))
new_li.sort(key=li.index)
print(new_li)
#结果:[1, 2, 3, 4, 5]
(3)遍历,保证了列表的顺序性
orgList = [1,0,3,7,7,5]
formatList = []
for id in orgList:
if id not in formatList:
formatList.append(id)
2.将列表当作队列使用(先进先出)
- 队列中第一加入的元素,第一个取出来
- 使用列表实现队列的功能如果用collections包里面的deque方法会更好
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")
>>> queue.append("Graham")
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
3.将列表当做堆栈使用(后进先出)
- 堆栈中最先进入的元素最后被释放(后进先出)。
- 用 append()可把元素添加到堆栈顶。用不指定索引的pop()可把一个元素从堆栈顶释放出来。
例:
stack = [3, 4, 5]
out=stack.pop()
#结果:5
4.轮询列表时remove元素遇到的坑
例1:删除a中的b元素
a = [1,2,2,3,4,4,5,6]
b=[2,4]
for i in a:
if i in b:a.remove(i)
print(a)
#结果:[1, 2, 3, 4, 5, 6]
原因:在上述for循环中,假设我们删除了index=1的值,原本index=2及之后的值会向前补位,所以在循环中就跳过了原index=2的变量
实现方法:
0.最好方法采用while list 循环 代替 for循环 ,如例2
1.若想循环删除列表中的元素,可用一个临时列表保存待删除的元素,在for循环临时列表来删除老列表中的元素;或者直接用剩余元素列表覆盖原列表
2.反向筛选,即选出不属于b中的元素,插入一新列表中
例2:
import random
la= [1,2,2,3,4,4,5,6]
while la:
url=random.choice(la)
la.remove(url)
print(url,len(la))
5.列表均匀切块
l = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]
print([l[i:i + 3] for i in range(0, len(l), 3)])
# [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']]
6.列表倒序(倒转)三种方法
lists = [1,3,4,5,6,7,9,2]
# 切片
print lists[::-1]
# 函数reverse 对数组进行操作
lists.reverse()
print lists
# 函数reversed 返回一个迭代对象,需要list化
print list(reversed(lists))
7.列表交集差集并集
(1)获取两个list 的交集
#方法一:
a=[2,3,4,5]
b=[2,5,8]
tmp = [val for val in a if val in b]
#方法二
print list(set(a).intersection(set(b)))
(2) 获取两个list 的并集
a=[2,3,4,5]
b=[2,5,8]
c=a+b
或
list(set(a).union(set(b)))
(3)获取两个 list 的差集
list(set(b).difference(set(a)))
#b中有而a中没有的