The beauty of python 1,beautypython
寫python已經差不多有三個多月了,因為簡潔,越來越喜歡這個"巨莽"了,我相信絕大多數人同樣喜歡簡潔。
今天第一次記錄,是我剛剛再工作上遇到的一個小問題,為了更方便理解,我把問題概括成這樣:
我有三百多萬條記錄,但是裡面有重複(裡面由數字和數字組成),我想要得到不重複的資料。
這是一個老問題,用c++的話很自然就會用到set,大概寫法就是
#include<iostream>#include<set>#include<string>#include<cstdio>using namespace std;int main(){ freopen("record.txt","r",stdin); freopen("uniquerec.txt","w",stdout); set<string> st; string mstr; while(cin>>mstr){ st.insert(mstr); } for(set<string>::iterator itr=st.begin();itr!=st.end();itr++){ cout<<*itr<<endl; } fclose(stdin); fclose(stdout); }
而用python,則是這樣的
#!/usr/bin/env python# coding=utf-8rec=open('record1.txt','r').readlines()uniquerec=open('unique.txt','w')st=set(rec)uniquerec.write(''.join(st))
怎麼樣?是不是讓人十分喜歡?短短几行,包括了讀寫檔案,過濾重複!
為了讓不熟悉py的同學明白,我簡單說一下用到的。
讀寫檔案就是open('檔案名稱字',參數[r為讀,w為寫,a為追加]')
用readlines()會返回一個列表
而利用列表lst建立集合則只需要
st=set(lst)
而'字串'.join是十分好用的串連,利用字串來串連容器內的元素,我用的是Null 字元,就是直接串聯起來。
之後,因為我的文件分開了兩個儲存,所以需要求並運算。py只需要這麼做。
#!/usr/bin/env python# coding=utf-8rec=open('record1.txt','r').readlines()rec2=open('record2.txt','r').readlines()uniquerec=open('unique.txt','w')st=set(rec)|set(rec2)uniquerec.write(''.join(st))沒錯,就是 | 用於求並,同理&則是求交 ,-是求差,^是求補。
python的簡潔和高效你感受到了嗎?
人生苦短,我用python!!
簡明python一個執行個體不解?
用python自己的zip庫: zlib 或 zipfile
後一個比較進階,推進。具體用法看這篇博文
blog.chinaunix.net/u1/39578/showart_356627.html
=====================
import zipfile, os
z = zipfile.ZipFile(filename, 'w') # 注意這裡的第二個參數是w,這裡的filename是壓縮包的名字
#假設要把一個叫testdir中的檔案全部添加到壓縮包裡(這裡只添加一級子目錄中的檔案):
if os.path.isdir(testdir):
for d in os.listdir(testdir):
z.write(testdir+os.sep+d)
# close() 是必須調用的!
z.close()
參考資料:blog.chinaunix.net/u1/39578/showart_356627.html
python 定義一個函數!!!!
def shiftingLetters(st,shift): ret=[] a=ord('a') z=ord('z') for i in st: if ord(i) in range(a,z+1): ret.append(chr(a+((ord(i)+shift-a)%26))) else: ret.append(i) return ''.join(ret)