前言
对 python 常用的一些数据结构进行说明整理
一、列表 list
1.1 基本操作
list = [1, 2, 3, 'A', 'B', 'C']
list.append('D') # 添加
list.insert(1, '1.5') # 指定位置添加
list.pop( ) # 删除最后一个元素
list.remove('C') # 删除指定值
list.pop(1) # 删除指定位置
len(list) # 返回列表长度
1.2 列表排序
list.sort( )
sorted(list)
list.reverse( ) # 倒序
1.3 遍历查看
# 方式一
for v in list:
print(v)
# 方式二
for i in range(len(list)):
print ("index = %s,value = %s" % (i, list[i]))
# 方式三
for i, v in enumerate(list):
print ("index = %s,value = %s" % (i, v))
1.4 列表转集合(去重)
list1 = [6, 7, 7, 8, 8, 9]
set(list1) # {6, 7, 8, 9}
1.5 两个列表转字典
list1 = ['key1', 'key2', 'key3']
list2 = ['1', '2', '3']
dict(zip(list1, list2)) # {'key1': '1', 'key2': '2', 'key3': '3'}
1.6 嵌套列表转字典
list3 = [['key1', 'value1'], ['key2', 'value'2], ['key3', 'value3']]
dict(list3) # {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
1.7 列表、元组转字符串
list4 = ['a', 'b', 'c']
''.join(list4) # 'abc'
tup1 = ('a', 'b', 'c')
''.join(tup1) # 'abc'
1.8 列表 A、B 相同与不同元素
set(A) & set(B) # 相同元素
set(A) ^ set(B) # 不同元素
1.9 列表表达式
有了列表表达式,就不需要用 for loop 来生成一个 list 了
[ expression for item in list if conditional ]
其中的 expression 可以直接生成 list,也可以使用表达式,做一些数学运算,甚至可以调用一个外部函数。最后,也可以在生成 list 时用 if 条件进行筛选。
二、元组 tuple
tuple 和 list 非常相似,但是 tuple 不能修改(约束强)
2.1 基本操作
tuple = (1, 2, 3, 'A', 'B', 'C')
tuple = ([1, 2, 3, 'A', 'B', 'C'], 4, 'D')
list = ([1, 2, 3, 'A', 'B', 'C']) # 元组中只有1个列表,这种写法结果变成了列表,不是元组,也不是集合
print(tuple) # 查看
tuple = tuple + ('D',) # 虽不能直接改,但可与其他方法添加
del tuple # 删除元组
2.2 遍历查看(与 list 一样)
# 方式一
for v in tuple:
print(v, end=’’)
# 方式二
for i in range(len(tuple)):
print ("index = %s,value = %s" % (i, tuple[i]))
# 方式三
for i, v in enumerate(tuple):
print ("index = %s,value = %s" % (i, v))
三、字典 dict
3.1 基本操作
dict = {
'name':'kk', 'age':100}
print(dict['age']) # 查看value
print(dict.keys())
dict['age'] = 18 # 修改
dict['birthday'] = '1900-01-01' # 添加
del dict['birthday'] # 删除键值对
3.2 遍历查看
# 方式一
for k in dict:
print('%s = %s' % (k, dict[k]))
# 方式二
for k in dict.keys():
print('%s = %s' % (k, dict[k]))
# 方式三
for k, v in dict.items():
print('%s = %s' % (k, v))
3.3 列表中存放字典
a = [{
"name": "mm", "age": 10}, {
"name": "qq", "age": 20}, {
"name": "hh", "age": 50}]
# 遍历列表
for item in a:
print(item, item['name'])
3.4 字典转换为字符串
dict1 = {
'a': 1, 'b': 2}
str(dict1) # '{'a': 1, 'b': 2}'
3.5 字典 key 和 value 相互转换
dict2 = {
'a': 1, 'b': 2, 'c': 3}
{
value: key for key, value in dict2.items()} # {1: 'a', 2: 'b', 3: 'c'}
3.6 字典推导式
d = {
key: value for (key, value) in iterable}
3.7 字典的合并
如果有重复的 key,那么第一个字典的这个 key 对应的值会被覆盖掉。
dict1 = {
'a':1, 'b':2}
dict2 = {
'c':4, 'b':3}
merged = {
**dict1, **dict2}
print(merged)
四、集合 set
集合元素不重复
4.1 基本操作
myset1 = set([1, 2, 3, 'A', 'B', 'C'])
myset2 = set([1, 2, 'B', 'C'])
print(myset1) # 查看
myset1.add('D') # 添加,{1, 2, 3, 'C', 'A', 'B', 'D'}
myset1.remove('D') # 删除
myset1.pop() # 移除最早值(类似于队列)
myset1 | myset2 # 并集
myset1 & myset2 # 交集
myset1 - myset2 # 差集
4.2 遍历查看
# 方式一
for v in myset:
print(v)
# 方式二
for i, v in enumerate(myset):
print('index = %s, value = %s' % (i, v))
五、字符串 string
5.1 基本操作
s = 'aabbcc'
list(s) # 字符串列表 ['a'', 'a', 'b', 'b', 'c', 'c']
tuple(s) # 字符串转元组 ('a', 'a', 'b', 'b', 'c', 'c')
set(s) # 字符串转集合 {'a', 'b', 'c'}
dict2 = eval("{'name:' ljq, 'age:': 24}") # 字符串转字典
5.2 切分字符串
a = 'a b c'
a.split(' ') # ['a', 'b', 'c']
5.3 字符串反转
a = 'string'
print(a[::-1])
5.4 去除空格
str1 = ' abcdefg'
str2 = 'abcdefg '
str1.strip() # 去除 str 两端空格 (strip())
str1.lstrip() # 去除 str 左端空格 (lstrip())
str2.rstrip() # 去除 str 右端空格 (rstrip())
# str 空格替换(replace(), 推荐使用)
str0 = ' a b c d e f g '
print(str0.replace(' ', ','))
# str 重新组合替换空格(使用split分割字符后重新组合,效率低)
str = ' a b c d e f g '
print(','.join(str.split(' ')))
# 正则表达式去除空格(用 sub() 方法替换)
import re
str = ' a b c d e f g '
print(re.sub(' ', ',', str))
5.5 把一个字符串列表变成一个字符串
mylist = ['The', 'quick', 'brown', 'fox']
mystring = " ".join(mylist)
六、数组
6.1 基本操作
from numpy import *
arr1 = array([2, 2, 2]) # 数组
arr2 = array([2, 3, 5])
arr3 = arr1 + arr2 # 数组相加
arr4 = arr1 * arr2 # 数组相乘
print(arr3)
print(arr4)
6.2 多维数组
arr5 = array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(arr5) # 查看多维数组
print(arr5[1, 0]) # 查看多维数组的指定元素
print(arr5[1][0]) # 查看多维数组的指定元素
七、矩阵
7.1 基本操作
import numpy as np
mat0 = np.mat([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(mat0)
7.2 嵌套列表转为矩阵
list = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],]
mat1 = np.mat(list) # np.matrix 函数名发生变化
print(mat1)
7.3 数组转为矩阵
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
mat2 = np.mat(arr)
print(mat2)
mat = np.mat(np.ones(3, 4)) # 3 行 4列值为 1 的矩阵
mat = np.mat(eye(4, 4, dtype=int)) # 对角矩阵