vivion32 发表于 2017-4-24 11:00:34

python--数据结构

数据结构:学列类型(列表,元组,字符串),集合(set),映射类型(字典)


列表
myList=[‘as’,123,‘dfg’]          #定义
myList.append(‘ddd’)               #添加
for item in myList:                  #遍历
print(item)

myList.sort()          #排序
len(myList)             #计算长度
del myList          #删除

堆栈:            myList.pop()

元组
zoo = (‘aa’, ‘bb’)         #小括号可以省略
len(zoo)=2                   #元组长度2
newzoo=’cc’,zoo
len(newzoo)=2                #长度还是2            ‘cc’,(‘aa’, ‘bb’)
newzoo=’bb’         #访问

字典
dic={‘key1’:’value1’,
‘key2’:’value2’,
‘key3’:’value3’
}
del dic[‘key1’]                         #删除
for key,value in dic.items():         #遍历
print(key,value)
dic[‘key4’]=’value4’             #添加
dic.has_key(‘keyName’)         #是否含有该key

集合
bri=set([‘aa’,’bb’])                      #定义
‘aa’in bri=True                               #是否含有该元素
bric=bri.copy()                                  #复制
bric.add(‘cc’)                                 #添加
bric.issuperset(bri)=True               #子集判断 / 包含于判断
bri.remove(‘bb’)                               #删除元素
bric & bir={‘aa’}#bri.intersection(bric)={‘aa’}      #求交集

引用
shopList=[‘a’,’b’,’c’]
myList=shopList                              #引用
del shopList                                          #删除
print(shopList)=print(myList)=[‘b’,’c’]         #结果一致,因为是引用

myList=shopList[:]                              #以全切片新建一个拷贝
del shopList                                          #删除
print(shopList) != print(myList)         #不相等,因为指向不同的对象

字符串
name=’abcd’
name.startswith(‘ab’)
name.find(‘bc’) != -1
delimiter=’_*_’
list=[‘1’,’2’,’3’]
print(delimiter.join(list))=1_*_2_*_3

reverse=name[::-1]=’dcba’ #反转字符串, 列表也可以

类-OOP
##每个函数定义时,第一个形参必须为self

class Persion:
num=0                         #类变量 每个对象共享
def __init__(self, name):   #初始化函数
self.name = name
def sayHi(self):            #自定义函数
print(‘my name is ’,self.name)

p = Person(‘lucy’)
p.sayHi()
>>my name is lucy

##python中所有类成员都为public
除了双下划线开头的:   __nameXXX,为private
惯例:单下划线开头的:_nameXXX,约定为private,但其实是public

文件操作
f = open(‘open.txt’,’w’)      #写模式打开文件
f.write(‘aaaaa’)                     #写文件
f.close()                                 #关闭文件

f=open(‘open.txt’)                  #默认读模式
whlie True:
line=f.readline()
if len(line) == 0:                #长度为0代表EOF
break
print(line,end=’’)
f.close()

with open(‘open.txt’) as f:
for line in f:
print(line,end=’’)

lambda 表达式             #返回新的函数对象
def make_repeater(n):
return lambda s : s*n

twice = make_repeater(2)
print(twice(‘word’))
print(twice(5))
>>wordword
>>10

列表解析
list=
newlist=
print(newlist)
>> 6, 8

函数接收元组+列表
def function_name(arg1, *args):
for i in args:
print(i)

def function_name(arg1, **args):
for key, value in args.items():
print(key, value)
页: [1]
查看完整版本: python--数据结构