1.

cities = ['Marseille', 'Amsterdam', 'New York', 'Londom']

# the good way
for i, city in enumerate(cities):
print(i, city)

2.

x_list = [1, 2, 3]
y_list = [2, 4, 6] # the good way
for x, y in zip(x_list, y_list):
print (x, y)

3.

x = 10
y = -10 # the good way
x, y = y, x
print ('After: x = %d, y = %d' % (x, y))

4.

ages = {
'Mary' : 31,
'Honathan' : 28
} # the good way
age = ages.get('Dick', 'Unknow')
print ('Dick is %s years old' % age)

5.

needle = 'd'
haystack = ['a', 'b', 'c', 'd']
# the good way
for letter in haystack:
if needle == letter:
print ('Found!')
break
else:
print ('Not found!')

6.

# the good way
with open('pimpin-aint-easy.txt') as f:
for line in f:
print (line)

7.

print ('Converting!')
try:
print (int(''))
except:
print ('Conversion failed!')
else:
print ('Conversion uccessful!')
finally:
print ('Done!')

8.

普通的方法,第一个参数需要是self,它表示一个具体的实例本身。
如果用了staticmethod,那么就可以无视这个self,而将这个方法当成一个普通的函数使用。
而对于classmethod,它的第一个参数不是self,是cls,它表示这个类本身。
>>> class A(object):
def foo1(self):
print "Hello",self
@staticmethod
def foo2():
print "hello"
@classmethod
def foo3(cls):
print "hello",cls

9.  Goal: Check if my version is the latest

lastest_python = 3
my_python = 2
msg = 'Update available' if lastest_python > my_python else 'Up to daye'
print('Update check: {}'.format(msg)) latest_python = [3, 5, 2]
my_python = [3, 5, 1]
msg = 'Update available' if latest_python > my_python else 'Up to date'
print('Update check: {}'.format(msg)

10. python之字符串格式化(format)

用法:

  它通过{}和:来代替传统%方式

1、使用位置参数

要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表

>>> li = ['hoho',18]
>>> 'my name is {} ,age {}'.format('hoho',18)
'my name is hoho ,age 18'
>>> 'my name is {1} ,age {0}'.format(10,'hoho')
'my name is hoho ,age 10'
>>> 'my name is {1} ,age {0} {1}'.format(10,'hoho')
'my name is hoho ,age 10 hoho'
>>> 'my name is {} ,age {}'.format(*li)
'my name is hoho ,age 18'

2、使用关键字参数

要点:关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可

>>> hash = {'name':'hoho','age':18}
>>> 'my name is {name},age is {age}'.format(name='hoho',age=19)
'my name is hoho,age is 19'
>>> 'my name is {name},age is {age}'.format(**hash)
'my name is hoho,age is 18'

3、填充与格式化

:[填充字符][对齐方式 <^>][宽度]

>>> '{0:*>10}'.format(10)  ##右对齐
'********10'
>>> '{0:*<10}'.format(10) ##左对齐
'10********'
>>> '{0:*^10}'.format(10) ##居中对齐
'****10****'

4、精度与进制

>>> '{0:.2f}'.format(1/3)
'0.33'
>>> '{0:b}'.format(10) #二进制
'1010'
>>> '{0:o}'.format(10) #八进制
'12'
>>> '{0:x}'.format(10) #16进制
'a'
>>> '{:,}'.format(12369132698) #千分位格式化
'12,369,132,698'

5、使用索引

>>> li
['hoho', 18]
>>> 'name is {0[0]} age is {0[1]}'.format(li)
'name is hoho age is 18

11.  Goal: Check if my version is the latest

# Ordered by population
cities = ['Groningen', 'Marseille', 'Paries', 'Buenos Aires', 'Mumbai'] smallest, *rest, largest = cities print('smallest: {}'.format(smallest))
print('largest: {}'.format(largest))

12.  未知数量参数

def draw_curve(*curves):
fig, axes = plt.subplots(nrows=1, figsize=(10, 8))
for curve_i, curve_name in enumerate(curves):
。。。

python tricks的更多相关文章

  1. Python Tricks 若干

    赵斌 - APRIL 29, 2015 在 python 代码中可以看到一些常见的 trick,在这里做一个简单的小结. json 字符串格式化 在开发 web 应用的时候经常会用到 json 字符串 ...

  2. Python tricks(7) -- new-style class的__slots__属性

    __slots__是在python 2.2开始引入的一个新特性, 我们来看一下官方给出的解释. This class variable can be assigned a string, iterab ...

  3. Python tricks(6) -- python代码执行的效率

    python作为一个动态语言, 本身学习曲线比较平滑, 效率相比起来会比c++和java低一些. 脚本语言都是运行时编译的, 这个对于效率的影响是非常大的. 我借用参考1的代码, 加了点代码impor ...

  4. Python tricks(5) -- string和integer的comparison操作

    我们都知道, python是一个强类型的语言, 也是一个动态类型的语言. 但是在python2.X系列中, 这个强类型是需要打折扣的, 是非常接近强类型. 我们来看下面的代码片段 In [1]: 'a ...

  5. Python tricks(4) -- with statement

    简介 with是从2.5版本引入的一个语法. 这个语法本身是为了解决try..finally繁琐的释放各类资源(文件句柄, Lock等)的问题. 如果想在旧版本中使用这个功能, 直接引入future模 ...

  6. Python tricks(3) -- list和dict的遍历和方法

    每个人在使用python的过程中都会遍历list和dict. List遍历 最常用最简单的遍历list的方法 a = ["a", "b", "c&qu ...

  7. Python tricks(2) -- method默认参数和闭包closure

    Python的method可以设置默认参数, 默认参数如果是可变的类型, 比如list, map等, 将会影响所有的该方法调用. 下面是一个简单的例子 def f(a=None, l=[]): if ...

  8. Python tricks(1) -- 动态定义一个新变量

    python是动态语言, 无需声明变量即可使用. 传递一个tuple, list或者dict等等方式, 有时候这种方式的使用不是很好. 对于tuple和list来说都是用下标的访问方式(即使用[]), ...

  9. Some Python Tricks

    python 的包管理很不好用,理解费力,故偷懒,模块仍按文件布局,写一个合并脚本将各个模块合并输出到一个脚本文件,分别管理,合并输出,回避了加载模块的问题 f-format 仅在python 3.6 ...

随机推荐

  1. HTTPS SSL/TLS协议

    要说清楚 HTTPS 协议的实现原理,至少需要如下几个背景知识.1. 大致了解几个基本术语(HTTPS.SSL.TLS)的含义2. 大致了解 HTTP 和 TCP 的关系(尤其是“短连接”VS“长连接 ...

  2. wiredtiger--初学数据恢复

    启动mongodb是failed,日志如下 1.解压wirdtiger包 tar -vxf wiredtiger-3.1.0.tar.bz2 -C /home/wiredtiger/ 2.安装snap ...

  3. IOC 和DI(转载)

    IOC 是什么? Ioc—Inversion of Control,即“控制反转”,不是什么技术,而是一种设计思想.在Java开发中,Ioc意味着将你设计好的对象交给容器控制,而不是传统的在你的对象内 ...

  4. jquery抓娃娃机代码

    <html><head><title>jQuery抓娃娃机游戏代码 - 源码之家</title><meta name="content- ...

  5. Linux 上pcntl安装步骤

    一. 下载对应的PHP源码包 wget http://cn2.php.net/get/php-5.5.20.tar.gz/from/this/mirror 二. 解压下载的源码文件 tar -zxvf ...

  6. 46 【golang项目】完成了一个小小的播放器功能

    项目地址:https://github.com/helww/mylab/tree/master/go/player 这个项目中用到了readme说明文件是一个markdown文件. 基础的控制语法,网 ...

  7. lenet-5

    https://blog.csdn.net/happyorg/article/details/78274066 深度学习 CNN卷积神经网络 LeNet-5详解 2017年10月18日 16:04:3 ...

  8. c#: WebBrowser控件html代码注入及交互

    主题仍是下载相关. 页面加载完成后,注入html元素,以使能够与主程序交互.并使WebBrowser与js交互,可以实现一些有趣的功能. 欲使WebBrowser与js交互,其所在页面类,须加上[Co ...

  9. layui禁止某些导航菜单展开

    官网上查得监听导航菜单的点击 当点击导航父级菜单和二级菜单时触发,回调函数返回所点击的菜单DOM对象: element.on('nav(filter)', function(elem){ consol ...

  10. java并发编程艺术

    cas算法 概要 刚开始看这本书的时候很经常看到cas算法,个人觉得cas算法在并发编程中也是挺重要的的一部分,cas是比较并交换的意思(compare and swap),campareAndSwa ...