你們以為我在學C++?其實我在學 Python
原文 http://segmentfault.com/blog/pezy/1190000002499989
我會隨便說,C++ 近年來開始"抄襲" Python 么?我只會說,我在用 C++ 來學習 Python.
不信?來跟著我學?
字面量
Python 早在 2.6 版本中就支持將二進制作為字面量了 1 , 最近 C++14 逐步成熟,剛剛支持這么干 2 :
static const int primes = b10100000100010100010100010101100;
更不用說 Python 在 1.5 時代就有了 raw string literals 的概念 3 ,咱們 C++ 也不算晚,C++11里也有了類似做法:
const char* path = r"C:\Python27\Doc";
Range Loop
Python 寫for循環是一件非常舒暢的事情:
for x in mylist: print(x);
大家都知道了,C++11里我總算也能做同樣的事情了:
for (int x : mylist) std::cout << x;
類型自動推導
Python 中真的有類型的概念嗎?(笑
x = "Hello World" print(x)
C++11 也學會了這招,只不過保留了老太太的裹腳布(auto)。
auto x = "Hello World"; std::cout << x;
元組
Python 里的元組(tuple)讓人羨慕已久,這玩意 Python 從一開始就有了。
triple = (5, "Hello", True) print(triple[])
好嘛,我來用 C++11 照貓畫虎:
auto triple = std::make_tuple(5, "hello", true); std::cout << std::get<>(triple);
有人說了,Python 大法好,還能逆向解析成變量呢
x, y, z = triple
哼,C++難道不行?
std::tie(x, y, z) = triple;
Lists
Python 里,Lists 是內置類型 4 ,創建一個 list 無比簡單:
mylist = [1, 2, 3, 4] mylist.append(5);
以前我們可以說,這有啥,std::vector差不多也能干這事。可 Python 粉較真了,您能像上面那樣初始化嗎?這話讓 Bjarne Stroustrup 老爹聽到了,暗自羞愧,于是在 C++11 里整出了個initializer_list做出回應 5 。
auto mylist = std::vector<int>{1,2,3,4}; mylist.push_back(5);
可人又說了,Python 里創造個 Dictionary 簡單的跟什么一樣 6 。
myDict = {5: "foo", 6: "bar"} print(myDict[5])
切,C++ 本身就有map類型,現在又多了個哈希表unordered_map,更像了:
auto myDict = std::unordered_map<int, const char*>{ { 5, "foo" }, { 6, "bar" } }; std::cout << myDict[5];
Lambda 表達式
Python 祭出大神器,1994年就有的 Lambda 表達式:
mylist.sort(key = lambda x: abs(x))
C++11 開始了拙劣的模仿:
std::sort(mylist.begin(), mylist.end(), [](int x, int y){ return std::abs(x) < std::abs(y); });
而 Python 在 2001 年加了一把力,引入了 Nested Scopes 的技術 7 :
def adder(amount): return lambda x: x + amount ... print(adder(5)(5))
C++11 不甘示弱,整出了 capture-list 的概念 8 。
auto adder(int amount) { return [=](int x){ return x + amount; }; } ... std::cout << adder(5)(5);
內置算法
Python 里有諸多內置的強大算法函數,如filter:
result = filter(mylist, lambda x: x >= )
C++11 倒也可以用std::copy_if干同樣的事情:
auto result = std::vector<int>{}; std::copy_if(mylist.begin(), mylist.end(), std::back_inserter(result), [](int x) { return x >= 0; });
這樣的函數在<algorithm>中屢見不鮮,而且都在與 Python 中的某種功能遙相呼應:transform,any_of,all_of,min,max.
可變參數
Python 從一開始就支持可變參數了。你可以定義一個變參的函數,個數可以不確定,類型也可以不一樣。
def foo(*args): for x in args: print(x);foo(5, "hello", True)</pre>
C++11 里initializer_list可以支持同類型個數可變的參數( C++ Primer 5th 6.2.6 )。
void foo(std::initializer_list<int> il) { for (auto x : il) std::cout << x; } foo({4, 5, 6});看到這里,你是否發現用 C++ 學習 Python 也不失為一種很妙的方式呢? 從 這個問題 的答案,可以看出@Milo Yip 也是同道中人呢。
繼續
覺得不錯?想要大展拳腳? 看看這個 repo 吧。上面有更多的方式,教你用 C++ 來學習 Python.
參考資料: http://preshing.com/20141202/cpp-has-become-more-pythonic
</div> </div>本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!