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. ajax----tomact服务器运行

    一.菜鸟教程的代码本地运行 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  2. 用js控制 给一个input赋值之后,change事件不能捕获到,解决办法

    你用js给input赋值后要调用change方法 下面是jquery的写法 $('input#3').val("50"); $('input#3').change(); 自己试试吧

  3. scrapy+redis去重实现增量抓取

    class ProjectnameDownloaderMiddleware(object): # Not all methods need to be defined. If a method is ...

  4. 看到blackarch 字体不错 记录下来

    terminus-font

  5. Yii 框架不同逻辑处理方法统一事务处理

    1.定义事务处理接口 <?php namespace frontend\business\SaveRecordByransactions; /** * Interface ISaveForTra ...

  6. 丑数(python)

    题目描述 把只包含质因子2.3和5的数称作丑数(Ugly Number).例如6.8都是丑数,但14不是,因为它包含质因子7. 习惯上我们把1当做是第一个丑数.求按从小到大的顺序的第N个丑数.   # ...

  7. 【python原理解析】python中分片的实现原理及使用技巧

    首先:说明什么是序列? 序列中的每一个元素都会被分配一个序号,即元素的位置,也称为索引:在python中的序列包含:字符串.列表和元组 然后是:什么是分片? 分片就是通过操作索引访问及获得序列的一个或 ...

  8. 366. Find Leaves of Binary Tree输出层数相同的叶子节点

    [抄题]: Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all ...

  9. centos7 smplayer 安装 安装视频播放器

    # yum -y install http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noar ...

  10. MySQL开发——【多表关系、引擎、外键、三范式】

    多表关系 一对一关系 一对多或多对一关系 多对多关系 MySQL引擎 所谓的MySQL引擎就是数据的存储方式,常用的数据库引擎有以下几种: Myisam与InnoDB引擎之间的区别(面试) ①批量插入 ...