转自 http://www.cnblogs.com/BeginMan/p/3164937.html 一.列表解析 列表解析来自函数式编程语言(haskell),语法如下: [expr for iter_var in iterable] [expr for iter_var in iterable if cond_expr] 第一种语法:首先迭代iterable里所有内容,每一次迭代,都把iterable里相应内容放到iter_var中,再在表达式中应用该iter_var的内容,最后用表达式的计算…
motorcycles = ["honda", "yamaha", "suzuki"] first_owned = motorcycles.pop(0) print("The first motorcycle I owned was a " + first_owned.title() + ".") 输出为: The first motorcycle I owned was a Honda.…
bicycles = ['trek','cannondale','redline','specialized'] message = "My first bicycle was a " + bicycles[0].title() + "." print(message) 输出为: My first bicycle was a Trek.…
with 语句和上下文管理器for.while 和 try 语句的 else 子句 with 语句会设置一个临时的上下文,交给上下文管理器对象控制,并且负责清理上下文.这么做能避免错误并减少样板代码,因此 API 更安全,而且更易于使用.除了自动关闭文件之外,with 块还有很多用途 else 子句不仅能在 if 语句中使用,还能在 for.while 和 try 语句中使用 for 仅当 for 循环运行完毕时(即 for 循环没有被 break 语句中止)才运行 else 块.while 仅…