我會隨便說,C++ 近年來開始"抄襲" Python 麼?我只會說,我在用 C++ 來學習 Python.html
不信?來跟着我學?python
Python 早在 2.6 版本中就支持將二進制做爲字面量了[1], 最近 C++14 逐步成熟,剛剛支持這麼幹[2]:git
static const int primes = 0b10100000100010100010100010101100;
更不用說 Python 在 1.5 時代就有了 raw string literals 的概念[3],我們 C++ 也不算晚,C++11裏也有了相似作法:github
const char* path = r"C:\Python27\Doc";
Python 寫 for
循環是一件很是舒暢的事情:算法
for x in mylist: print(x);
你們都知道了,C++11裏我總算也能作一樣的事情了:app
for (int x : mylist) std::cout << x;
Python 中真的有類型的概念嗎?(笑函數
x = "Hello World" print(x)
C++11 也學會了這招,只不過保留了老太太的裹腳布(auto
)。oop
auto x = "Hello World"; std::cout << x;
Python 裏的元組(tuple
)讓人羨慕已久,這玩意 Python 從一開始就有了。學習
triple = (5, "Hello", True) print(triple[0])
好嘛,我來用 C++11 照貓畫虎:spa
auto triple = std::make_tuple(5, "hello", true); std::cout << std::get<0>(triple);
有人說了,Python 大法好,還能逆向解析成變量呢
x, y, z = triple
哼,C++難道不行?
std::tie(x, y, z) = triple;
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];
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 >= 0)
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)
C++11 增長了對參數包的支持。但與 Python 的不一樣在於:只能在編譯期經過模板來使用,而不像 Python 那樣在運行期做爲單個對象來使用。
template <typename... T> auto foo(T&&... args) { return std::make_tuple(args...); } auto triple = foo(5, "hello", true);
看到這裏,你是否發現用 C++ 學習 Python 也不失爲一種很妙的方式呢? 從這個問題的答案,能夠看出 @MiloYip 也是同道中人呢。
繼續
以爲不錯?想要大展拳腳? 看看這個 repo 吧。上面有更多的方式,教你用 C++ 來學習 Python.
參考資料:http://preshing.com/20141202/cpp-has-become-more-pythonic