每天读一篇一线开发者原创好文
来源:pezy
segmentfault.com/a/1190000002499989
我会随便说,C++ 近年来开始”抄袭” Python 么?我只会说,我在用 C++ 来学习 Python.
不信?来跟着我学?
字面量
Python 早在 2.6 版本中就支持将二进制作为字面量了[1], 最近 C++14 逐步成熟,刚刚支持这么干[2]:
staticconstintprimes=0b10100000100010100010100010101100;
更不用说 Python 在 1.5 时代就有了 raw string literals 的概念[3],咱们 C++ 也不算晚,C++11里也有了类似做法:
constchar*path=r"C:\Python27\Doc";
Range Loop
Python 写 for 循环是一件非常舒畅的事情:
forxinmylist:
print(x);
大家都知道了,C++11里我总算也能做同样的事情了:
for(intx:mylist)
std::cout
类型自动推导
Python 中真的有类型的概念吗?(笑
x="Hello World"
print(x)
C++11 也学会了这招,只不过保留了老太太的裹脚布(auto)。
autox="Hello World";
std::cout
元组
Python 里的元组(tuple)让人羡慕已久,这玩意 Python 从一开始就有了。
triple=(5,"Hello",True)
print(triple[])
好嘛,我来用 C++11 照猫画虎:
autotriple=std::make_tuple(5,"hello",true);
std::cout(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]。
automylist=std::vector{1,2,3,4};
mylist.push_back(5);
可人又说了,Python 里创造个 Dictionary 简单的跟什么一样[6]。
myDict={5:"foo",6:"bar"}
print(myDict[5])
切,C++ 本身就有 map 类型,现在又多了个哈希表 unordered_map,更像了:
automyDict=std::unordered_map{{5,"foo"},{6,"bar"}};
std::cout
Lambda 表达式
Python 祭出大神器,1994年就有的 Lambda 表达式:
mylist.sort(key=lambdax:abs(x))
C++11 开始了拙劣的模仿:
std::sort(mylist.begin(), mylist.end(), [](int x, int y){ return std::abs(x)
而 Python 在 2001 年加了一把力,引入了 Nested Scopes 的技术[7]:
def adder(amount):
returnlambdax:x+amount
...
print(adder(5)(5))
C++11 不甘示弱,整出了 capture-list 的概念[8]。
auto adder(intamount){
return[=](intx){returnx+amount;};
}
...
std::cout
内置算法
Python 里有诸多内置的强大算法函数,如 filter:
result=filter(mylist,lambdax:x>=)
C++11 倒也可以用 std::copy_if 干同样的事情:
autoresult=std::vector{};
std::copy_if(mylist.begin(),mylist.end(),std::back_inserter(result),[](intx){returnx>=;});
这样的函数在 中屡见不鲜,而且都在与 Python 中的某种功能遥相呼应:transform, any_of, all_of, min, max.
可变参数
Python 从一开始就支持可变参数了。你可以定义一个变参的函数,个数可以不确定,类型也可以不一样。
def foo(*args):
forxinargs:
print(x);
foo(5,"hello",True)
C++11 增加了对参数包的支持。但与 Python 的不同在于:只能在编译期通过模板来使用,而不像 Python 那样在运行期作为单个对象来使用。
templateauto foo(T&&...args){
returnstd::make_tuple(args...);
}
autotriple=foo(5,"hello",true);
看到这里,你是否发现用 C++ 学习 Python 也不失为一种很妙的方式呢? 从这个问题的答案(http://zhihu.com/question/26477210/answer/32936952),可以看出 @MiloYip 也是同道中人呢。
继续
觉得不错?想要大展拳脚? 看看这个 repo (https://github.com/ryanhaining/cppitertools) 吧。上面有更多的方式,教你用 C++ 来学习 Python.
参考资料:http://preshing.com/20141202/cpp-has-become-more-pythonic
领取专属 10元无门槛券
私享最新 技术干货