本节详细介绍python中列表的用法,列表是python中最重要的数据结构,python程序员必须熟练掌握。
(本节原计划包含集合、字典等内容,但因列表知识点较多,还是不涉及其他内容较好。)
列表基本
letters = [‘a’, ‘b’, ‘c’]
matrix = [[0, 1], [2, 3]]
# 二维列表
zero = [0]*5
print(zero)
# 输出很魔幻:[0, 0, 0, 0, 0]
combined = zero+letters
print(combined)
# 列表中各元素类型不必都一样,可以有数字和字符或其他
# 输出 [0, 0, 0, 0, 0, ‘a’, ‘b’, ‘c’]
numbers = list(range(20))
# list函数用于转换成列表
print(numbers)
# 输出 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
print(numbers[::2])
# 间隔2输出:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
print(numbers[::-1])
# -1 表示倒序输出:[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
chars = list(‘Hello world’)
print(len(chars))
# 输出 11
列表拆包
列表拆包是指将列表项分配给变量,这几乎是现代语言的标配
numbers = [1, 2, 3]
first, second, third = numbers
print(first, second, third)
# first,second,third分别为1,2,3
numbers = [1, 2, 3, 4, 4, 4, 4, 9]
first, *other, last = numbers
print(first, other, last)
# first,other,last分别为1,[2, 3, 4, 4, 4, 4],9
first, second, *other = numbers
print(first, second, other)
# first,second,other分别为1,2,[3, 4, 4, 4, 4, 9]
循环列表
letters = [“a”, “b”, “c”]
for index, letter in enumerate(letters):
print(index, letter)
# enumerate的作用是将列表拆分成(0,”a”)这样的可迭代元组
# for循环中index,letter是将各元组拆包
# 元组是只读列表,本节后面会说到
添加或删除列表项
python全都是对象,是对象就有方法,列表通过一些方法添加和删除列表项。
letters = [“a”, “b”, “c”]
letters.append(“d”)
# 在末尾添加,输出 [‘a’, ‘b’, ‘c’, ‘d’]
letters.insert(0, “_”)
# 在指定位置添加,输出 [‘_’, ‘a’, ‘b’, ‘c’, ‘d’]
letters.pop()
# 末尾删除,相当于堆栈出栈,输出 [‘_’, ‘a’, ‘b’, ‘c’]
letters.pop(0)
# 删除指定位置,输出 [‘a’, ‘b’, ‘c’]
letters.remove(“b”)
# 删除指定的列表项,找到第一个删除,输出 [‘a’, ‘c’]
del letters[0:3]
# 删除指定范围的列表项
letters.clear()
# 清除所有列表项
查找列表项
letters = [“a”, “b”, “c”]
print(letters.count(“d”))
if “d” in letters:
print(letters.index(“d”))
# index方法返回查找的列表项的索引位置
# 不存在如果就调用index方法将出错,所以恰当的做法是先检测是否存在
列表排序
numbers = [3, 51, 2, 8, 6]
numbers.sort()
# 列表sort方法进行排序,输出 [2, 3, 6, 8, 51]
print(numbers)
numbers.sort(reverse=True)
# 倒序输出 [51, 8, 6, 3, 2]
print(numbers)
print(sorted(numbers))
print(sorted(numbers, reverse=True))
# 内置函数sorted也可对列表进行排序
# 但它不改变原列表
前面排序的列表项是数字,显然可以判断大小。但列表项如果是对象,该如何判断呢?需定义排序函数,这也是现代语言的标配。
items = [
(“Product1”, 10),
(“Product2”, 9),
(“Product3”, 12),
]
# 定义一个列表,列表项为元组,这里每一项包含产品和价格
def sort_item(item):
return item[1]
# 定义排序函数sort_item
items.sort(key=sort_item)
# 传递排序函数进行排序
print(sorted(items, key=sort_item,reverse=True))
# 内置函数sorted也用排序函数
Lambda函数
lambda函数,是一个简单的单行匿名函数。
python语言中lambda的语法是:
lambda parameters:expression
主要用于简化函数的编写,比如可以代替前面的排序函数sort_item,直接写在排序语句里即可:
items.sort(key=lambda item: item[1])
lambda函数应用极广,在现代开发场景中,几乎是必备知识,比如在javascript es6及之后的版本中就使用 箭头函数作为lambda函数。
map函数
map是内置函数,它操作可迭代的对象比如列表。对每一项进行计算并作为新的可迭代对象的子项。map函数返回的也是可迭代对象。
items = [
(“Product1”, 10),
(“Product2”, 9),
(“Product3”, 12),
]
prices = list(
map(lambda item: item[1], items)
)
print(prices)
# 输出 [10, 9, 12]
初学者可能有点难理解,但map函数、接下来的filter函数及lambda函数是必须熟练掌握的,否则就不会是合格的python程序员。
filter函数
filter与map类似,它过滤出符合条件的迭代项。
items = [
(“Product1”, 10),
(“Product2”, 9),
(“Product3”, 12),
]
filtered = list(
filter(lambda item: item[1] >= 10, items)
)
print(filtered)
# 输出价格大于等于10的产品列表
# [(‘Product1’, 10), (‘Product3’, 12)]
列表推导
这可能是python中最独特的语法,在现代其他语言中貌似都没类似的用法。
用法是:
[expression for item in items]
每次迭代 expression表达式根据item得出新子项,并作为新的列表项。
它可以代替 map或filter:
prices = [item[1] for item in items]
# 实现了map函数的功能
filtered = [item for item in items if item[1] >= 10]
# 实现了filter函数的功能
zip函数
合并多个列表,变成以元组为列表项的单个列表
list1 = [1, 2, 3]
list2 = [10, 20, 30]
print(list(
zip(“abc”, list1, list2)
))
# 输出 [(‘a’, 1, 10), (‘b’, 2, 20), (‘c’, 3, 30)]
用列表实现堆栈
使用列表的append实现压栈
使用列表的pop实现出栈
查栈顶可以用 [-1]检查
检查是否为空的例名:
if list:
pop()
用列表实现队列
与堆栈一样,可以使用列表的原生功能实现。但是,队列是从头部删除的,如果队列较长,每出列一个,后面全部都要向前移动,开销比较大。
可以引入deque来解决开销问题。
from collections import deque
queue = deque([])
# 初始化一个空队列
queue.append(1)
queue.append(2)
queue.append(3)
queue.append(4)
queue.append(5)
# …
queue.popleft()
# 出列
if not queue:
# 判断是否是空队列
print(“emptys”)
元组
元组就是只读的列表,用小括号表示。
point = (1, 2)
也可以省略小括号,如:
point = 1, 2
功能与列表一样,但不能有赋值,增加、删除列表项等修改的行为。
来看个其他编程语言“不可能”的操作:如果需要交换变量值,一般都需要一个中间变量来暂存,但在python中是不需要的,用元组轻松搞定,可读性也更强。
x = 10
y = 11
x, y = y, x
print(x, y)
# x变成11,y变成10了
# 原因:右边会被包装成元组,然后拆包赋给左边的x和y,实现了交换
数组array
绝大部分情况下用列表就能搞定,但在列表项有大量数据时可能会出现性能问题,这时可以考虑使用array
from array import array
numbers = array(“i”, [1, 2, 3])
# “i” 表示array内的元素类型是整数
numbers.append(4)
numbers.append(5)
numbers.append(6)
numbers.append(7)
# …
# array的用法与列表是一样的,但有一个条件,array内的类型是一样的。
# 这里的typecode设了”i”,表示是整数,那么只能存整数
# 如果存其他类型将出错
numbers[0] = 4.0
# 存浮点数将出错
小结
本篇详细讲解了python中最重要的数据结构–列表的用法。
下一篇计划讲解集合、字典及异常处理。敬请关注。