Python实用技巧

1、改变工作目录

1 import os
2 os.chdir('C:/Users/Mr.Zhao')

2、搜索制定目录下的文件

1 import glob
2 glob.glob('C:/User/Mr.Zhao/*.csv')

3、对字典进行排序

1 dict_test = {'Zhao':1,'Zhou':2,'Zheng':3}
2 sorted(dict_test.items(), key = lambda x : x[0], reverse = True)

    结果为:[('Zhou', 2), ('Zheng', 3), ('Zhao', 1)]

4、对一个列表中的不同类别计数

1 import collections
2 list_test = ['a','b','b','c','c','c','d','d','d','d']
3 collections.Counter(list_test)

5、random模块中随机抽取

1 from random import choice
2 list_test=[1,2,3,4]
3 choice(list_test)     #每次抽取list_test中的一个,每次取值不同
4 
5 
6 from random import sample
7 num = range(10000)
8 sample(num,100)   #每次抽取100个

6、计时工具

import timeit
def test_func():
    x = range(100000)
    return x

timeit.timeit(test_func, number = 1)  #准确测量test_func()函数执行时间

7、对列表元素去重

 1 test= [1,1,2,2,3,3,4,4,4]
 2 
 3 #方法一
 4 list(set(test))
 5 
 6 #结果为   [1, 2, 3, 4]
 7 
 8 
 9 #方法二
10 {}.fromkeys(test).keys()
11 
12 #结果为   dict_keys([1, 2, 3, 4])

8、设置python中默认的编码

1 import sys
2 
3 if sys.getdefaultencoding() != 'utf-8' :
4     reload(sys)
5     sys.setdefaultencoding('utf-8')
6 else:
7     pass

9、find 和 rfind 函数(用于查找字符串中某一个字符的位置)

1 str = "abcdefghijkd"
2 
3 str.find("d")     #默认从左侧开始查找
4 
5 #结果为  3
6 
7 str.rfind("d")    #rfind()从右侧开始查找
8 
9 #结果为  11

10、numpy模块中的concatenate()函数

 1 import numpy as np
 2 
 3 test = [
 4            np.array([1,2,3])
 5           ,np.array([4,5,6,7])
 6           ,np.array([9,10])
 7           ]
 8 
 9                    #输出为 [array([1, 2, 3]), array([4, 5, 6, 7]), array([ 9, 10])]
10 
11 np.concatenate(test)
12  
13 #此时test输出为 array([1,  2,  3,  4,  5,  6,  7,  9, 10])
原文地址:https://www.cnblogs.com/myblog1993/p/8297895.html