A few things to remember while coding in Python.
A few things to remember while coding in Python.
- 17 May 2012 -
UPDATE: There has been much discussion in Hacker News about this article. A few corrections from it.
Zen of Python
Learning the culture that surrounds a language brings you one step closer to being a better programmer. If you haven’t read the Zen of Python yet open a Python prompt and type
import this. For each of the item on the list you can find examples here http://artifex.org/~hblanks/talks/2011/pep20_by_example.htmlOne caught my attention:
Beautiful is better than ugly
Give me a function that takes a list of numbers and returns only the even ones, divided by two.
#----------------------------------------------------------------------- halve_evens_only = lambda nums: map(lambda i: i/2, filter(lambda i: not i%2, nums)) #----------------------------------------------------------------------- def halve_evens_only(nums):
return [i/2 for i in nums if not i % 2]
Remember the very simple things in Python
Swaping two variables:
a, b = b, a
The step argument in slice operators. For example:
a = [1,2,3,4,5]
>>> a[::2] # iterate over the whole list in 2-increments
[1,3,5]
The special case
x[::-1]is a useful idiom for ‘x reversed’.>>> a[::-1]
[5,4,3,2,1]
UPDATE: Do keep in mind
x.reverse()reverses the list in place and slices gives you the ability to do this:>>> x[::-1]
[5, 4, 3, 2, 1] >>> x[::-2]
[5, 3, 1]
Don’t use mutables as defaults
def function(x, l=[]): # Don't do this def function(x, l=None): # Way better
if l is None:
l = []
UPDATE: I realise I haven’t explained why. I would recommend reading the article by Fredrik Lundh. In short it is by design that this happens. “Default parameter values are always evaluated when, and only when, the “def” statement they belong to is executed;”
Use
iteritemsrather thanitemsiteritemsusesgeneratorsand thus are better while iterating through very large lists.d = {1: "1", 2: "2", 3: "3"} for key, val in d.items() # builds complete list when called. for key, val in d.iteritems() # calls values only when requested.
This is similar with
rangeandxrangewherexrangeonly calls values when requested.UPDATE: Do note that the
iteritems,iterkeys,itervaluesare removed from Python 3.x. Thedict.keys(),dict.items()anddict.values()return views instead oflists. http://docs.python.org/release/3.1.5/whatsnew/3.0.html#views-and-iterators-instead-of-listsUse
isinstancerather thantypeDon’t do
if type(s) == type(""): ...
if type(seq) == list or \
type(seq) == tuple: ...
rather:
if isinstance(s, basestring): ...
if isinstance(seq, (list, tuple)): ...
For why not to do so: http://stackoverflow.com/a/1549854/504262
Notice I used
basestringand notstras you might be trying to check if a unicode object is a string. For example:>>> a=u'aaaa'
>>> print isinstance(a, basestring)
True
>>> print isinstance(a, str)
False
This is because in Python versions below 3.0 there are two string types
strandunicode:object
|
|
basestring
/ \
/ \
str unicode
Learn the various
collectionsPython has various container datatypes which are better alternative to the built-in containers like
listanddictfor specific cases.Generally most use this:
UPDATE: I’m sure most do not use this. Carelessness from my side. A few may consider writing it this way:
freqs = {}
for c in "abracadabra":
try:
freqs[c] += 1
except:
freqs[c] = 1
Some may say a better solution would be:
freqs = {}
for c in "abracadabra":
freqs[c] = freqs.get(c, 0) + 1
Rather go for the
collectiontypedefaultdictfrom collections import defaultdict
freqs = defaultdict(int)
for c in "abracadabra":
freqs[c] += 1
Other collections
namedtuple() # factory function for creating tuple subclasses with named fields
deque # list-like container with fast appends and pops on either end
Counter # dict subclass for counting hashable objects
OrderedDict # dict subclass that remembers the order entries were added
defaultdict # dict subclass that calls a factory function to supply missing values
UPDATE: As noted by a few in Hacker News I could have used
Counterinstead ofdefaultdict.>>> from collections import Counter
>>> c = Counter("abracadabra")
>>> c['a']
5
When creating classes Python’s magic methods
__eq__(self, other) # Defines behavior for the equality operator, ==.
__ne__(self, other) # Defines behavior for the inequality operator, !=.
__lt__(self, other) # Defines behavior for the less-than operator, <.
__gt__(self, other) # Defines behavior for the greater-than operator, >.
__le__(self, other) # Defines behavior for the less-than-or-equal-to operator, <=.
__ge__(self, other) # Defines behavior for the greater-than-or-equal-to operator, >=.
There are several others.
Conditional Assignments
x = 3 if (y == 1) else 2 It does exactly what it sounds like: "assign 3 to x if y is 1, otherwise assign 2 to x". You can also chain it if you have something more complicated: x = 3 if (y == 1) else 2 if (y == -1) else 1
Though at a certain point, it goes a little too far.
Note that you can use if … else in any expression. For example:
(func1 if y == 1 else func2)(arg1, arg2)
Here
func1will be called if y is 1 andfunc2, otherwise. In both cases the corresponding function will be called with arguments arg1 and arg2.Analogously, the following is also valid:
x = (class1 if y == 1 else class2)(arg1, arg2)
where
class1andclass2are two classes.Use the
Ellipsiswhen necessary.UPDATE: As one commenter mentioned in Hacker News “Using Ellipsis for getting all items is a violation of the Only One Way To Do It principle. The standard notation is
[:].” I do agree with him. A better example is given using numpy in stackoverflow:The ellipsis is used to slice higher-dimensional data structures.
It’s designed to mean at this point, insert as many full slices (:) to extend the multi-dimensional slice to all dimensions.
Example:
>>> from numpy import arange
>>> a = arange(16).reshape(2,2,2,2)
Now, you have a 4-dimensional matrix of order 2x2x2x2. To select all first elements in the 4th dimension, you can use the ellipsis notation
>>> a[..., 0].flatten()
array([ 0, 2, 4, 6, 8, 10, 12, 14])
which is equivalent to
>>> a[:,:,:,0].flatten()
array([ 0, 2, 4, 6, 8, 10, 12, 14])
Previous suggestion.
When creating a class you can use
__getitem__to make you class’ object work like a dictionary. Take this class as an example:class MyClass(object):
def __init__(self, a, b, c, d):
self.a, self.b, self.c, self.d = a, b, c, d def __getitem__(self, item):
return getattr(self, item) x = MyClass(10, 12, 22, 14)
Because of
__getitem__you will be able to get the value ofain the objectxbyx['a']. This is probably a known fact.This object is used to extend the Python slicing.(http://docs.python.org/library/stdtypes.html#bltin-ellipsis-object). Thus if we add a clause:
def __getitem__(self, item):
if item is Ellipsis:
return [self.a, self.b, self.c, self.d]
else:
return getattr(self, item)
We can use
x[...]to get a list containing all the items.>>> x = MyClass(11, 34, 23, 12)
>>> x[...]
[11, 34, 23, 12]
A few things to remember while coding in Python.的更多相关文章
- machine learning in coding(python):使用贪心搜索【进行特征选择】
print "Performing greedy feature selection..." score_hist = [] N = 10 good_features = set( ...
- Python Coding Interview
Python Coding Interview Python Advanced Use enumerate() to iterate over both indices and values Debu ...
- Python 3.4 send mail
#coding=utf-8 #Python 3.4 https://docs.python.org/3.4/library/ #IDE:Visual Studio 2015 Window10 impo ...
- Artificial intelligence(AI)
ORM: https://github.com/sunkaixuan/SqlSugar 微软DEMO: https://github.com/Microsoft/BotBuilder 注册KEY:ht ...
- Python基础算法综合:加减乘除四则运算方法
#!usr/bin/env python# -*- coding:utf-8 -*-#python的算法加减乘除用符号:+,-,*,/来表示#以下全是python2.x写法,3.x以上请在python ...
- [No000078]Python3 字符串操作
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '''Python 字符串操作 string替换.删除.截取.复制.连接.比较.查找.包含.大小写转换.分 ...
- python for MSSQLserver
# -*- coding: utf-8 -*- '''python coded by written in 2016/8/31 Used for get win os log for each win ...
- python for mysql
# -*- coding: utf-8 -*- '''python coded by written in 2016/8/31 Used for get win os log for each win ...
- python3 实现简单的信用卡还款,取款转账功能V2
仅实现还款,取款,转账,信息查询功能 程序结构: atm(函数主执行程序): #Author by Andy #_*_ coding:utf-8 _*_ import os,sys Father_pa ...
随机推荐
- 使用C#代码发起K2 Blackpearl流程
转:http://www.cnblogs.com/dannyli/archive/2011/08/02/2125285.html 使用C#代码,发起一个K2的流程,其形式和链接SQL Server数据 ...
- 简单的聊天程序,主要用到的是Socket
服务端: import java.io.*; import java.net.*; import java.util.*; public class ChatServer { boolean stat ...
- redmine 2.5.2 安装后邮件无法发送
找到redmine安装目录-apps->redmine->htdocs->conflg->configuration.yml email_delivery: delive ...
- hdu 4539(状态压缩dp)
题意:曼哈顿距离是指:|x1-x2|+|y1-y2|,只要知道这个概念题意就懂了. 分析:这道题与前面做的几道题有所不同,因为当前行不仅与前一行有关,而且与前两行有关,所以我们开数组的时候还要记录前两 ...
- 多数据源问题--Spring+Ibatis 访问多个数据源(非分布式事务)
有的时候,我在一个工程中需要访问两个以上的数据源,尤其是在系统集成的时候,以下是我在系统集成的时候遇到的情况,我的工程的架构是:spring2.0+ibatis2.0+struts1.2. 数据库是o ...
- Golang几个常用记录日志对比
go语言有一个标准库,log,提供了最基本的日志功能,但是没有什么高级的功能,如果需要高级的特性,就需要使用第三方包,下面是一些候选的包: go_tmlog https://code.google.c ...
- Golang 绘图基础- 不同的输出源
先看一个简单代码, 它执行后会产生下面的300*500的png图片文件: 代码: 1: package main 2: 3: import ( 4: "fmt" 5: " ...
- leetcode:Integer to Roman(整数转化为罗马数字)
Question: Given an integer, convert it to a roman numeral. Input is guaranteed to be within the rang ...
- Ubuntu14.04LTS安装记录(办公室联想台式机)
一.用UltraISO制作U盘启动器,被安装的电脑要设置成从U盘启动. 二.傻瓜式安装简体中文版 三.安装更新 sudo apt-get update sudo apt-get upgrade 四.安 ...
- vs2008编译boost
vs2008编译boost [一.Boost库的介绍] Boost库是一个经过千锤百炼.可移植.提供源代码的C++库,作为标准库的后备,是C++标准化进程的发动机之一.Boost库由C++标准委员会库 ...