Python 学习笔记 3:数据结构(列表、字典)

列表

列表是 Python 中基本的数据结构,列表中的每个元素都分配一个数字——索引(位置),第一个索引是 0,第二个索引是 1, 以此类推。
列表的数据项不需要具有相同的类型。

列表基本操作

创建一个列表,只要把逗号分隔的不同数据项使用方括号括起来即可。

# 新建列表
testlist = [10086, '中国移动', [1,2,3,4,5]]
print('testlist: ', testlist)   # testlist:  [10086, '中国移动', [1, 2, 3, 4, 5]]
print()
# 访问列表长度
print('len(testlist): ', len(testlist))  # len(testlist):  3

可以使用下标索引来访问列表中的值(正序和倒序都可),同样也可以使用方括号的形式截取元素。

# 从第二个元素 访问到 列表结尾
print('testlis[1:]: ', testlist[1:])  # testlis[1:]:  ['中国移动', [1, 2, 3, 4, 5]]
# 向列表添加元素
testlist.append({})
# testlist.append({}) 后:  [10086, '中国移动', [1, 2, 3, 4, 5], {}]
print('testlist.append({}) 后: ', testlist) 
# 列表的最后一个元素
print('testlist[-1]: ', testlist[-1])  # testlist[-1]:  {}
# 弹出确定位置的列表元素
testlist.pop(1)
print('testlist.pop(1) 后: ', testlist)  # testlist.pop(1) 后:  [10086, [1, 2, 3, 4, 5], {}]
# 更新列表元素
testlist[0] = 1008611
print('testlist[0] = ', testlist[0]) # testlist[0] = 1008611
# 使用 del 删除列表元素
print('原始列表: ', testlist)  # 原始列表: [10086, [1, 2, 3, 4, 5], {}]
del testlist[2]
print('删除第三个元素后的列表: ', testlist)  # 删除第三个元素后的列表: [10086, [1, 2, 3, 4, 5]]

列表脚本操作符

[1,2,3]+[4,5,6]

结果为 [1,2,3,4,5,6],用于组合列表。

['Hi']*4

结果为 [‘Hi’,‘Hi’,‘Hi’,‘Hi’],用于重复列表。

3 in [1,2,3]

结果为 True,判断元素是否存在于列表中。

列表函数和方法

len(list)----- 列表元素的个数
max(list)----- 返回列表元素的最大值
min(list)----- 返回列表元素的最小值
list(seq)----- 将元组转化为列表
list.append(obj)---------- 在列表末尾添加新的对象
list.count(obj)----------- 统计某个元素在列表中出现的次数
list.extend(seq)---------- 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.index(obj)----------- 从列表中找出某个值第一个匹配项的索引位置
list.insert(index, obj)--- 将对象插入列表的特定位置
list.pop([index=-1])------ 移除列表中的一个元素(默认最后一个元素,可以改),并返回该元素的值
list.remove(obj)---------- 移除列表中某个值的第一个匹配项
list.reverse()------------ 反向列表中元素
list.clear()-------------- 清空列表
list.copy()--------------- 复制列表
list.sort(key=None, reverse=False)-- 对原列表进行排序,默认是正序

列表构成矩阵

# 列表构成矩阵
matrix = [[1,2,3],
          [4,5,6],
          [7,8,9]]
print('matrix: ', matrix)  # matrix:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print('matrix[1]: ', matrix[1])  # matrix[1]:  [4, 5, 6]
print('matrix[1][1]: ', matrix[1][1])  # matrix[1][1]:  5
print()
col2 = [row[1] for row in matrix]
print('col2 = [row[1] for row in matrix]: ', col2)  # col2 = [row[1] for row in matrix]:  [2, 5, 8]
col2even = [row[1] for row in matrix  if row[1] % 2 == 0]
# col2even = [row[1] for row in matrix  if row[1] % 2 == 0]:  [2, 8]
print('col2even = [row[1] for row in matrix  if row[1] % 2 == 0]: ', col2even)

列表转化为字符串

temp_list = ['H', 'e', 'l', 'l', 'o']
result = ''.join(temp_list)
print(result)    # Hello

常用操作性能

按索引取值和赋值 ( v=a[i], a[i]=v )
由于列表的随机访问特性,这两个操作执行时间与列表大小无关,均为 O ( 1 ) O(1) O(1)

列表增长,append() ,__add__() "+"
list.append(v) , 执行时间是 O ( 1 ) O(1) O(1)
list= list +[v] , 执行时间是 O ( n + k ) O(n+k) O(n+k),其中 k k k 是被加的列表长度。

OperationBig-O Efficiency
index []O(1)
index assignmentO(1)
appendO(1)
pop()O(1)
pop(i)O(n)
insert(i, item)O(n)
del operatorO(n)
iterationO(n)
contains(in)O(n)
get slice [x : y]O(k)
del sliceO(n)
set sliceO(n+k)
reverseO(n)
concatenateO(k)
sort(归并)O(n log n)
multiplyO(nk)

字典

字典也是一种可变容器模型,且可以存储任意类型对象。
字典的每个键值对(key->value)用冒号()分隔,每对之间用逗号()分隔,整个字典包括在花括号({})中

d = {key1:value1, key2:value2, ...}

在字典中,键必须是唯一的,但是值不必是唯一的创建时如果同一个键被赋值两次,后一个值会被记住
值可以取任何数据类型;但是键必须是不可以变的,可以是如字符串、数字或者元组,而列表不可以,因为列表可变。

访问字典中的值

可以通过相应的键索引来访问字典中的值,如果字典中没有相应的键索引,则会导致 Traceback

字典内置函数和方法

len(dict) : 计算字典元素的个数,即键的总数。

>>> dict = {'Name': 'Firefox', 'Age': 2020, 'Class': 'Seven'}
>>> len(dict)
3

str(dict) : 输出字典,以可打印的字符串表示。

>>> dict = {'Name': 'Firefox', 'Age': 2020, 'Class': 'Seven'}
>>> str(dict)
"{'Name': 'Firefox', 'Age': 2020, 'Class': 'Seven'}"

type(variable) : 返回输入的变量类型,如果变量是字典就返回字典类型。

>>> dict = {'Name': 'Firefox', 'Age': 2020, 'Class': 'Seven'}
>>> type(dict)
<class 'dict'>

radiansdict.clear() : 删除字典内的所有元素;
radiansdict.copy() : 返回字典的一个浅复制;
radiansdict.fromkeys(seq) :创建一个新字典,以序列 seq 中的元素作为字典的键,value 为字典所有键对应的初始值;
radiansdict.get(key, default=None) : 返回指定键的值,如果键不在字典中就返回 default 设置的默认值;

key in dict : 如果键在字典 dict 中就返回 true;否则就返回 false
radiansdict.items() : 以列表返回可遍历的 (键,值) 元组数组;
radiansdict.keys() :返回一个迭代器,可以使用 list() 来转化为列表;
radiansdict.setdefault(key, default=None) : 和 get() 类似,但是如果键不存在于字典中,将会添加键并将值设为 default

radiansdict.update(dict2) :把字典 dict2 的键值对更新到 dict 中;
radiansdict.values() : 返回一个迭代器,可以使用 list() 来转化为列表;
pop(key[,default]) : 删除字典给定键 key 所对应的值,返回值为被删除的值;key 值必须给出,否则返回 default 值;
popitem() : 返回并删除字典中的最后一对键值。

字典与列表

类型listdict
索引自然数 i不可变类型值 key
添加append 、extend、insertb[k] = v
删除pop、removepop
更新a[i] = vb[k] = v
正查a[i]、a[i : j]b[k]、copy
反查index(v) 、count(v)
其他reverse 、sorthas_key 、update
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值