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. Redis核心原理

    Redis系统介绍: Redis的基础介绍与安装使用步骤:https://www.jianshu.com/p/2a23257af57b Redis的基础数据结构与使用:https://www.jian ...

  2. C语言递归函数讲解

    递归函数是什么? 是函数.................... 你可以把它理解成是for循环与死循环的结合的函数.简单的说:递归函数是有条件终止的死循环函数: 死循环函数这里是指在函数体中调用自身: ...

  3. android studio 创建图标

    参考 https://www.cnblogs.com/c546170667/p/5975550.html File-New-Image Asset

  4. 错误:libstdc++.so.6: wrong ELF class

    1.安装mysql的时候报错缺少GLIBCXX_3.4.15 2.按照网上的下载了libstdc++.so.6.0.17 放到/usr/lib64 下 删除之前的libstdc++.so.6的链接 重 ...

  5. Linux LVM扩容和缩容

    将原硬盘上的LVM分区/dev/mapper/RHEL-Data由原来的60G扩展到80G Step1:将LVData扩容+20G,如下图: [root@esc data]# lvextend -L ...

  6. webapi 重复提交问题

    https://izen.live/Blog/info/13.html /// <summary> /// action方法过滤器 /// </summary> public ...

  7. Node.js web发布到AWS ubuntu 之后,关闭Putty,Node 项目也随之关闭的解决办法

    最近公司把BlockChain和对应的Node Web都发布到了AWS 的ubuntu 系统上. 但是遇到了一个问题,每次启动 Node Web之后,关闭Putty,Node Web也随之关闭. 由于 ...

  8. 201621123002《JAVA程序设计》第四周学习总结

    1. 本周学习总结 1.1 写出你认为本周学习中比较重要的知识点关键词 继承 多态 覆盖 抽象 重载 1.2 尝试使用思维导图将这些关键词组织起来.注:思维导图一般不需要出现过多的字. 1.3 可选: ...

  9. echo 转义字符的使用

    man echo 查看 echo 的使用文档 -n 不尾随换行符 -e 启用解释反斜杠的转义功能 -E 禁用解释反斜杠的转义功能(默认) --help 显示此帮助信息并退出 --version 显示版 ...

  10. SpringBoot小新手。

    2018-09-27 最近在学习SpringBoot:教材 先是在https://start.spring.io/下载了工程.demo.zip 下载之后,导入Eclipse工程,pom.xml里面的& ...