序列分类
序列可分为:不可变序列与可变序列
不变可变序列:字符串、元组
可变序列:列表、字典
可变序列:可以对序列执行增、删、改操作,对象地址不发生更改
元组的三种创建方式
'''元组的创建方式'''
'''第一种创建方式,使用()'''
t= ( 'Python' , 'world' , 98 )
print ( t)
print ( type ( t) )
t2= 'Python' , 'world' , 98
print ( t2)
print ( type ( t2) )
t3= ( 'Python' , )
print ( t3)
print ( type ( t3) )
'''第二种创建方式,使用内置函数tuple()'''
t1= tuple ( ( 'Python' , 'world' , 98 ) )
print ( t1)
print ( type ( t1) )
'''空元组的创建方式'''
'''空列表的创建方式'''
lst= [ ]
lst1= list ( )
d= { }
d2= dict ( )
t4= ( )
t5= tuple ( )
print ( '空列表' , lst, lst1)
print ( '空字典' , d, d2)
print ( '空元组' , t4, t5)
元素修改
t= ( 10 , [ 20 , 30 ] , 9 )
print ( t)
print ( type ( t) )
print ( t[ 0 ] , type ( t[ 0 ] ) , id ( t[ 0 ] ) )
print ( t[ 1 ] , type ( t[ 1 ] ) , id ( t[ 1 ] ) )
print ( t[ 2 ] , type ( t[ 2 ] ) , id ( t[ 2 ] ) )
'''尝试将t[1]修改为100'''
print ( id ( 100 ) )
'''由于[20,30]列表,而列表是可变序列,所以可以向列中添加元素,而列表的内存地址不变'''
t[ 1 ] . append( 100 )
print ( t, id ( t[ 1 ] ) )
元组的遍历
'''元组的遍历'''
t= ( 'Python' , 'world' , 98 )
'''第一种获取元组元组的方式,使用索引'''
print ( t[ 0 ] )
print ( t[ 1 ] )
print ( t[ 2 ] )
'''遍历元组'''
for item in t:
print ( item)
集合的定义与创建
集合
Python语言提供的内置数据结构 与列表、字典一样都属于可变类型的序列 集合是没有value的字典
'''第一种创建方式使用{}'''
s= { 2 , 3 , 4 , 5 , 5 , 6 , 7 , 7 }
print ( s)
'''第二种创建方式使用set()'''
s1= set ( range ( 6 ) )
print ( s1, type ( s1) )
s2= set ( [ 1 , 2 , 4 , 5 , 5 , 5 , 6 , 6 ] )
print ( s2, type ( s2) )
s3= set ( ( 1 , 2 , 4 , 4 , 5 , 65 ) )
print ( s3, type ( s3) )
s4= set ( 'python' )
print ( s4, type ( s4) )
s5= set ( { 12 , 4 , 34 , 55 , 66 , 44 , 4 } )
print ( s5, type ( s5) )
s6= { }
print ( type ( s6) )
s7= set ( )
print ( type ( s7) )
集合的相关操作
s= { 10 , 20 , 30 , 405 , 60 }
'''集合元素的判断操作'''
print ( 10 in s)
print ( 100 in s)
print ( 10 not in s)
print ( 100 not in s)
'''集合元素的新增操作'''
s. add( 80 )
print ( s)
s. update( { 200 , 400 , 300 } )
print ( s)
s. update( [ 100 , 99 , 8 ] )
s. update( ( 78 , 64 , 56 ) )
print ( s)
集合的包含关系
'''一个集合是否是另一个集合的子集'''
s1= { 10 , 20 , 30 , 40 , 50 , 60 }
s2= { 10 , 20 , 30 , 40 }
s3= { 10 , 20 , 90 }
print ( s2. issubset( s1) )
print ( s3. issubset( s1) )
'''一个集合是否是另一个集合的超集'''
print ( s1. issuperset( s2) )
print ( s1. issuperset( s3) )
'''两个集合是否含有交集'''
print ( s2. isdisjoint( s3) )
s4= { 100 , 200 , 300 }
print ( s2. isdisjoint( s4) )
集合的数学运算
s1= { 10 , 20 , 30 , 40 }
s2= { 20 , 30 , 40 , 50 , 60 }
print ( s1. intersection( s2) )
print ( s1 & s2)
print ( s1)
print ( s2)
print ( s1. union( s2) )
print ( s1| s2)
print ( s1)
print ( s2)
print ( s1. difference( s2) )
print ( s1- s2)
print ( s1)
print ( s2)
print ( s1. symmetric_difference( s2) )
print ( s1^ s2)
列表和集合生成式
lst= [ i* i for i in range ( 10 ) ]
print ( lst)
s= { i* i for i in range ( 10 ) }
print ( s)