我会随便说,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