0%

python技巧

无序记录python使用中的技巧,

centos6 安装python2.7

1
2
3
4
5
6
7
8
yum install -y zlib-devel bzip2-devel openssl-devel xz-libs wget mysql-devel 
wget https://www.python.org/ftp/python/2.7.8/Python-2.7.8.tgz
tar -zxvf Python-2.7.8.tgz
cd Python-2.7.8
./configure --prefix=/usr/local
make && make install
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
/usr/local/bin/python2.7 get-pip.py

python 字典比较

json_tools.diff()

python list filter (过滤list 中含有”topic”的元素,生成一个新的字典)

list(filter(lambda x: "topic" in x , confs_list)

判断变量是否存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

python中检测某个变量是否有定义

第一种方法使用内置函数locals():
locals():获取已定义对象字典

'testvar' in locals().keys()
1
第二种方法使用内置函数dir():
dir():获取已定义对象列表

'testvar' in dir()
1
第三种方法使用内置函数vars():
vars():获取已定义对象字典

vars().has_key('testvar')

lambda, filter, map

lambda 匿名函数

格式: fun_name = lambda x : x+2(表达式)

1
x=lambda x:x*x if x%2==0 else x

sort lambda (按照第三列排序)

l=[(‘b’, ‘atom’, 2), (‘c’, ‘big’, 12), (‘a’, ‘tom’, 21)]
l.sort(key=lambda l: (l[2]))
l
[(‘b’, ‘atom’, 2), (‘c’, ‘big’, 12), (‘a’, ‘tom’, 21)]