The beauty of python 1

寫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-8
rec=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是十分好用的連接,利用字符串來連接容器內的元素,我用的是空字符,就是直接串連起來。

之後,因爲我的文檔分開了兩個存儲,所以需要求並運算。py只需要這麼做。

#!/usr/bin/env python
# coding=utf-8
rec=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!!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章