非常有用的Python技巧

开发 后端
今天给大家介绍一个非常有用的Python技巧,一起来看一下吧。

 函数连续调用 

def add(x):  
    class AddNum(int):  
        def __call__(self, x): 
            return AddNum(self.numerator + x) 
     return AddNum(x)  
print add(2)(3)(5)  
# 10  
print add(2)(3)(4)(5)(6)(7)  
# 27  
# javascript 版  
var add = function(x){  
    var addNum = function(x){  
        return add(addNum + x);  
    };  
    addNum.toString = function(){  
        return x;  
    }  
    return addNum;  

add(2)(3)(5)//10  
add(2)(3)(4)(5)(6)(7)//27 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

默认值陷阱 

>>> def evil(v=[]):  
...     v.append(1)  
...     print v 
...  
>>> evil()  
[1]  
>>> evil()  
[1, 1] 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

读写csv文件 

import csv  
with open('data.csv', 'rb') as f:  
    reader = csv.reader(f)  
    for row in reader: 
         print row  
# 向csv文件写入  
import csv  
with open( 'data.csv', 'wb') as f:  
    writer = csv.writer(f)  
    writer.writerow(['name', 'address', 'age'])  # 单行写入  
    data = [  
            ( 'xiaoming ','china','10'),  
            ( 'Lily', 'USA', '12')]   
    writer.writerows(data)  # 多行写入 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

数制转换 

>>> int('1000', 2)  
 
>>> int('A', 16)  
10 
  • 1.
  • 2.
  • 3.
  • 4.

格式化 json 

echo'{"k": "v"}' | python-m json.tool 
  • 1.

list 扁平化 

list_ = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  
[k for i in list_ for k in i] #[1, 2, 3, 4, 5, 6, 7, 8, 9]  
import numpy as np  
print np.r_[[1, 2, 3], [4, 5, 6], [7, 8, 9]]  
import itertools  
print list(itertools.chain(*[[1, 2, 3], [4, 5, 6], [7, 8, 9]]))  
sum(list_, [])  
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]  
flatten(list_) 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

list 合并 

>>> a = [1, 3, 5, 7, 9]  
>>> b = [2, 3, 4, 5, 6]  
>>> c = [5, 6, 7, 8, 9]  
>>> list(set().union(a, b, c))  
[1, 2, 3, 4, 5, 6, 7, 8, 9] 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

出现次数最多的 2 个字母 

from collections import Counter  
c = Counter('hello world')  
print(c.most_common(2)) #[('l', 3), ('o', 2)] 
  • 1.
  • 2.
  • 3.

谨慎使用 

eval("__import__('os').system('rm -rf /')", {}) 
  • 1.

置换矩阵 

matrix = [[1, 2, 3],[4, 5, 6]] 
res = zip( *matrix )   # res = [(1, 4), (2, 5), (3, 6)] 
  • 1.
  • 2.

列表推导 

[item**2 for item in lst if item % 2]  
map(lambda item: item ** 2, filter(lambda item: item % 2, lst))  
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))  
['1', '2', '3', '4', '5', '6', '7', '8', '9'] 
  • 1.
  • 2.
  • 3.
  • 4.

排列组合 

>>> for p in itertools.permutations([1, 2, 3, 4]):  
...     print ''.join(str(x) for x in p)  
...  
1234  
1243  
1324  
1342  
1423  
1432  
2134  
2143  
2314  
2341  
2413  
2431  
3124  
3142  
3214  
3241  
3412  
3421  
4123  
4132  
4213  
4231  
4312  
4321  
>>> for c in itertools.combinations([1, 2, 3, 4, 5], 3):  
...     print ''.join(str(x) for x in c)  
...  
123  
124  
125  
134  
135  
145  
234  
235  
245  
345  
>>> for c in itertools.combinations_with_replacement([1, 2, 3], 2):  
...     print ''.join(str(x) for x in c)  
...  
11  
12  
13  
22  
23  
33  
>>> for p in itertools.product([1, 2, 3], [4, 5]):  
(1, 4)  
(1, 5)  
(2, 4)  
(2, 5)  
(3, 4)  
(3, 5) 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.

默认字典 

>>> m = dict()  
>>> m['a']  
Traceback (most recent call last):  
  File "<stdin>", line 1, in <module>  
KeyError: 'a'  
>>>  
>>> m = collections.defaultdict(int)  
>>> m['a']  
 
>>> m['b']  
 
>>> m = collections.defaultdict(str)  
>>> m['a']  
''  
>>> m['b'] += 'a'  
>>> m['b']  
'a'  
>>> m = collections.defaultdict(lambda: '[default value]')  
>>> m['a']  
'[default value]'  
>>> m['b']  
'[default value]' 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

反转字典 

>>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}  
>>> m  
{'d': 4, 'a': 1, 'b': 2, 'c': 3}  
>>> {v: k for k, v in m.items()}  
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}  
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

 

责任编辑:庞桂玉 来源: 马哥Linux运维
相关推荐

2023-02-19 15:22:22

React技巧

2009-02-09 11:20:06

Windows7Windows

2020-06-15 10:29:10

JavaScript开发 技巧

2021-10-30 18:59:15

Python

2013-06-14 14:57:09

Java基础代码

2025-02-13 08:06:54

2022-06-27 19:01:04

Python应用程序数据

2010-07-30 09:07:12

PHP函数

2011-07-07 17:16:43

PHP

2017-08-02 13:32:18

编程Java程序片段

2009-03-24 14:23:59

PHP类库PHP开发PHP

2011-04-06 14:08:14

jQuery

2025-02-26 11:05:03

2012-05-25 14:20:08

JavaScript

2022-09-02 23:08:04

JavaScript技巧开发

2023-06-13 15:15:02

JavaScript前端编程语言

2018-08-03 10:02:05

Linux命令

2013-11-05 10:03:22

Eclipse功能

2013-08-21 10:31:22

HTML5工具

2021-03-09 09:14:27

ES2019JavaScript开发
点赞
收藏

51CTO技术栈公众号