Python的内建数据结构

元组

元组是一种固定长度、不可变的python对象序列。

tup=4,5,6
nested_tup=(4,5,6),(7,8)#元素是元组的元组
tuple([4,0,2])#tuple函数将任意序列或迭代器转换为元组
tup=tuple('string')
tup[0]  //'s'
#元组中存储的对象其自身是可变的,但元组一旦创建,各个位置上的对象是无法被修改的
tup=tuple(['foo',[1,2],True])#('foo', [1, 2], True)
tup[2]=False#error
tup[1].append(3)#('foo', [1, 2, 3], True)
#使用+号连接元组来生成更长的元组
(4,None,'foo')+(6,0)+('bar',)#(4, None, 'foo', 6, 0, 'bar')
#将元组乘以整数,会生成含有多份拷贝的元组,注意对象自身没有复制,只是只想它们的引用进行了复制
('foo','bar')*4 #('foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar')

元组拆包

tup=4,5,6 
a,b,c=tup # a=4,b=5,c=6
a,b,(c,d)=4,5,(6,7) #a=4,b=5,c=6,d=7

#交换变量
a,b=1,2# a=1,b=2
b,a=a,b # a=2,b=1

seq=[(1,2,3),(4,5,6),(7,8,9)]
for a,b,c in seq:
    print('a={0},b={1},c={2}'.format(a,b,c))
#a=1,b=2,c=3
#a=4,b=5,c=6
#a=7,b=8,c=9

高级拆包

获取从元组的起始位置“采集”一些元素

values=1,2,3,4,5
a,b,*rest=values # a=1,b=2,reset=[3,4,5]

元组的方法

  1. count 计量某个数值在元组中出现的次数
a=(1,2,2,2,3,4,2)
a.count(2) # 4

列表

长度可变,内容可以修改

a_list=[2,3,7,None] # [2, 3, 7, None]
tup=('foo','bar','baz')
b_list=list(tup) # ['foo', 'bar', 'baz']
b_list[1]='peekaboo' # ['foo', 'peekaboo', 'baz']
gen=range(10)
list(gen) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#增加、移除元素
b_list.append('dwarf') #['foo', 'peekaboo', 'baz', 'dwarf']
b_list.insert(1,'red') #b_list=['foo', 'red', 'peekaboo', 'baz', 'dwarf']
b_list.pop(2) # 'peekaboo',b_list=['foo', 'red', 'baz', 'dwarf']

#remove 定位第一个符合要求的值并移除它
b_list.append('foo')
b_list.remove('foo')# b_list=['red', 'baz', 'dwarf', 'foo']

#使用in关键字检查一个值是否在列表中
'dwarf' in b_list #True
#与字典、集合相比,检查列表中是否包含一个值是非常缓慢的。这是因为python在列表中进行了线性逐个扫描,而在字典和集合中python是同事检查所有元素的(基于hash表)

#连接和联合列表
#使用+号连接列表
[4,None,'foo']+[7,8,(2,3)] # [4, None, 'foo', 7, 8, (2, 3)]
#使用extend方法向列表中添加多个元素 (更快)
x=[4,None,'foo']
x.extend([7,8,(2,3)]) # x=[4, None, 'foo', 7, 8, (2, 3)]

#排序
a=[7,2,5,1,3]
#默认是递增排序
#无需创建新对象
a.sort() #a=[1, 2, 3, 5, 7] 
b=['saw','small','He','foxes','six']
b.sort(key=len) #按长度递增排序

二分搜索和已排序列表的维护

内建模块bisect实现了二分搜索和已排序列表的插值。
bisect.bisect 会找到元素应当被插入的位置
bisect.insort 将元素插入到相应位置
bisect模块的函数不会检查列表是否已排序

import bisect
c=[1,2,2,2,3,4,7]
bisect.bisect(c,2) # 4
bisect.insort(c,6) # c=[1, 2, 2, 2, 3, 4, 6, 7]

切片

使用切片符号可以对大多数序列类型选取子元素,它的基本形式将是start:stop传入到索引符号[]中,包含起始值,不包含结束值

seq=[7,2,3,7,5,6,0,1]
seq[1:5] # [2, 3, 7, 5]
# start和stop可以省略
seq[:5] # [7, 2, 3, 7, 5]
seq[3:] # [7, 5, 6, 0, 1]
# 负索引可以从序列的尾部进行索引
seq[-4:] # [5, 6, 0, 1]
seq[-6:-2] # [3, 7, 5, 6]
# 步进值step可以在第二个冒号后面使用,意思是每隔多少个数取一个值
seq[::2] #[7, 3, 5, 0]
#当需要对列表或元组进行翻转时,一种很聪明的用法就是向步进传值-1
seq[::-1] #[1, 0, 6, 5, 7, 3, 2, 7]

python的内建序列函数

1 enumerate 遍历一个序列的同时跟踪当前元素的索引
enumerate函数,返回(i,value)元组的序列,其中value是值,i是元素的索引

some_list=['foo','bar','baz']
for i,value in enumerate(some_list):
    mapping[value]=i
# mapping={'foo': 0, 'bar': 1, 'baz': 2}

2 sorted 返回一个根据任意序列中元素新建的已排序列表

sorted([7,1,3,6,0,3,2]) # [0, 1, 2, 3, 3, 6, 7]

sorted函数接收的参数与列表的sort方法一致
3 zip 将列表、元组或其他序列的元素配对,新建一个元组构成的列表

seq1=['foo','bar','baz']
seq2=['one','two','three']
zipped=zip(seq1,seq2)
list(zipped) # [('foo', 'one'), ('bar', 'two'), ('baz', 'three')]
seq3=[False,True]
seq3=[False,True]
list(zip(seq1,seq2,seq3))  # [('foo', 'one', False), ('bar', 'two', True)]
# zip可以处理任意长度的序列,它生成列表长度由最短的序列决定
# zip的常用场景为同时遍历多个序列,有时也会和enumerate同时使用
for i,(a,b) in enumerate(zip(seq1,seq2)):
    print('{0}:{1},{2}'.format(i,a,b))
# zip拆分
pitchers=[('Nolan','Ryan'),('Roger','Clemens'),('Schilling','Curt')]
first_name,last_name=zip(*pitchers)
# first_name =('Nolan', 'Roger', 'Schilling')
# last_name =('Ryan', 'Clemens', 'Curt')

3 reversed 将序列元素逆序

list(reversed(range(10))) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

字典

empty_dict={}
d1={'a':'some value','b':[1,2,3,4]} #d1={'a': 'some value', 'b': [1, 2, 3, 4]}
d1[7]='an integer' # d1={'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer'}
d1['b'] # [1, 2, 3, 4]
'b' in d1 # 判断d1是否含有键'b'
d1[5]='some value'
d1['dummy']='another value' #d1=Out[101]:{'a': 'some value','b': [1, 2, 3, 4], 7: 'an integer', 5: 'some value', 'dummy':'another value'}
#使用del和pop删除值
del d1[5] # d1={'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer', 'dummy': 'another value'}
ret=d1.pop('dummy') #ret='another value' d1={'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer'}
list(d1.keys()) # ['a', 'b', 7]
list(d1.values()) # ['some value', [1, 2, 3, 4], 'an integer']
#使用update将两个字典合并
d1.update({'b':'foo','c':12}) # d1={'a': 'some value', 'b': 'foo', 7: 'an integer', 'c': 12}

#从序列生成字典
# 1
mapping ={}
for key,value in zip(key_list,value_list):
	mapping[key]=value
# 2
mapping=dict(zip(range(5),reversed(range(5)))) # mapping={0: 4, 1: 3, 2: 2, 3: 1, 4: 0}

#默认值
#带默认值的get会在参数不是字典的键时返回None,pop会抛出异常
value=some_dict.get(key,default_value)
value=some_dict.pop(key,default_value)
#方法1,2,3等效
#1
words=['apple','bat','bar','atom','book']
by_letter={}
for word in words:
    letter=word[0]
    if letter not in by_letter:
        by_letter[letter]=[word]
    else:
        by_letter[letter].append(word)
#2        
by_letter={}
for word in words:
    letter=word[0]
    by_letter.setdefault(letter,[]).append(word)
 #3   
from collections import defaultdict
by_letter=defaultdict(list)
for word in words:
    by_letter[word[0]].append(word)

字典的值可以是任何python对象,但键必须时不可变对象,比如变量类型(整数、浮点数、字符串)或元组(且元组内对象也必须是不可变对象)

集合

集合是一种无序且元素唯一的容器,集合的元素是不可变的。若想要包含列表型的元素,必须线转换为元组

#集合的创建方法
#集合{1, 2, 3}
set([2,2,2,1,3,3])
{2,2,2,1,3,3} 

#集合的操作
a.add(x) 将元素x加入集合a
a.clear() 将集合重置为空,清空所有元素
a.remove(x) 从集合中移除某个元素
a.pop() 移除任意元素,如果集合为空则抛出keyError
a.union(b) a|b a和b的并
a.update(b) a|=b 将a的内容设置为a和b的并
a.intersection(b) a&b
a.intersection_update(b) a&=b
a.difference(b) a-b
a.difference_update(b) a-=b
a.symmertric_difference(b) a^b # 所有在a或b,但又不同时在a、b的元素
a.symmertric_difference_update(b) a^=b
a.issubset(b) #判断a是否包含于b
a.issuperset(b) #判断a是否包含b
a.isdisjoint(b) #判断a,b是否没有交集 
# 当且仅当两个集合的内容一模一样时,两个集合才相等

列表、集合、字典的推导式

#列表的推导式
[expr for val in collection if condition]
#字典的推导式
{key_expr:value_expr for value in collection if condition}
#集合的推导式
{expr for value in collection if condition}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值