#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 1 fruit.extend(['apple','blana'])#add two print(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]) #set a_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 time a = [] 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和i lett = ['a','b','c','d'] for num,let in enumerate(lett): print (num,let) #class类 class TestA: attr = 1 def _init_(self): self.attr = 4 obj_a = TestA() print('result:',obj_a.attr)#结果是1,为什么不是4,(类属性和实例属性区别,值得思考,表示没想通) print(TestA.__dict__) print(obj_a.__dict__) class TestB: attr = 1 obj_b = TestB() obj_c = TestB() obj_b.attr = 10#attr私有属性 print(obj_c.attr) class TestC: atrr = 1 obj_d = TestC() TestC.atrr = 10 print(obj_d.atrr) #get lib path import sys print(sys.path) #use my own lib使用自己封装的库 import Mylib for name,sex in zip(Mylib.FakeUser.fake_name(30),Mylib.FakeUser.fake_name(30)): print(name,sex) #get locale encode style import locale print(locale.getpreferredencoding()) #file operation file_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 synchron print(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 = 0 with 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_cyj with open('/Users/cykj/Desktop/caoyajun.txt',mode ='a',encoding = 'utf-8') as file_cyj: file_cyj.write('\naaaaaaaaaaaaaaaa')
result: