python基础3

来源:互联网 发布:java中遍历数组 编辑:程序博客网 时间:2024/05/23 19:39
#list列表fruit =['pineapple','pear']fruit.insert(1,'grape')fruit[0:0] = "orange"print(fruit)fruit.remove('grape')print(fruit)del fruit[0:2]#del 0 and 1fruit.extend(['apple','blana'])#add twoprint(fruit)#dictionary字典NSSDAQ_code = {    'BD':'baidu',    'TX':'tenxun'}NSSDAQ_code['AL'] ='alibaba'NSSDAQ_code.update({'PW':'perfect world','WY':'wangyi'})del NSSDAQ_code['WY']print(NSSDAQ_code)#Tuple元组letters = ('a','b','c','d')print(letters[0])#seta_set ={1,2,3,4}a_set.add(5)print(a_set)a_set.discard(5)print(a_set)num_list =['6','3','7','2']char_list = ['aaaa','fff','erwew','ere']print(sorted(num_list,reverse=True),sorted(char_list))#列表的解析式import  timea = []t1 = time.clock()for i in range(1,20000):    a.append(i)print(time.clock() -t1,'s')b= []t2 =time.clock()b = [i for i in range(1,20000)]#推导式#解析式print(time.clock() -t2,'s')#result:# 0.004609000000000009 s#0.001346 s这个效率高#list 推导式a =[i*2 for i in range(1,6)]b =[i+1 for i in range(1,6)]c =[i for i in range(1,6) if i%2 ==0]print(a,b,c)#set 推导式d = {i:i+1 for i in range(4)}e = {i:j.upper() for i,j in zip(range(1,5),'abcd')}print(d,e)#遍历list,获取element和ilett = ['a','b','c','d']for num,let in enumerate(lett):    print (num,let)#class类class TestA:    attr = 1    def _init_(self):        self.attr = 4obj_a = TestA()print('result:',obj_a.attr)#结果是1,为什么不是4,(类属性和实例属性区别,值得思考,表示没想通)print(TestA.__dict__)print(obj_a.__dict__)class TestB:    attr = 1obj_b = TestB()obj_c = TestB()obj_b.attr = 10#attr私有属性print(obj_c.attr)class TestC:    atrr = 1obj_d = TestC()TestC.atrr = 10print(obj_d.atrr)#get  lib pathimport  sysprint(sys.path)#use my own lib使用自己封装的库import Mylibfor name,sex in zip(Mylib.FakeUser.fake_name(30),Mylib.FakeUser.fake_name(30)):    print(name,sex)#get locale encode styleimport localeprint(locale.getpreferredencoding())#file operationfile_caoyajun = open('/Users/cykj/Desktop/caoyajun.txt')print(file_caoyajun.name,file_caoyajun.encoding,file_caoyajun.mode,'\n',file_caoyajun.read())#name、encoding、access(r/w/x)#English use 1 byte,chinese use several size#seek()  and read() paramer  is  not synchronprint(file_caoyajun.read(),file_caoyajun.seek(0),file_caoyajun.read(1),file_caoyajun.read(3),file_caoyajun.tell(),)#读文件,文件起点,读一个byte,读3个byte,当前位置(注意一个汉字可能占几个byte)file_caoyajun.close()#actually the  file_caoyajun  is  not  release,just close  the file#solution:line_number = 0with open('/Users/cykj/Desktop/caoyajun.txt',mode ='r',encoding = 'utf-8') as  file_cyj: #note:':'represent  code block.    for a_line in  file_cyj:        line_number += 1
#前面有4个空格然后右对齐,过滤掉‘.\n’        print('{0:>4} {1}'.format(line_number,a_line.rstrip()))#rstrip  delete  '. \n'  {:>4} 右对齐 asign right at  most 4  space#python can  auto  to close  the file_cyjwith open('/Users/cykj/Desktop/caoyajun.txt',mode ='a',encoding = 'utf-8') as  file_cyj:    file_cyj.write('\naaaaaaaaaaaaaaaa')
result: