找找你所需要的python小技巧

45 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

list洗牌(将list打乱)

import random 
alist = [1,2,3,4,5]
random.shuffle(alist) 
print(alist) #[4, 2, 1, 3, 5]

对字典的value进行排序

sorted(d.items(),key=lambda x:x[1])

字符串转字典

str1 ="k:1|k1:2|k2:3|k3:4" 
def str2dict(str1): 
	dict1 = {} 
	for iterms in str1.split('|'): 
		key,value =iterms.split(':') 
		dict1[key] = value 
	return dict1 
#字典推导式 
d = {k:int(v) for t in str1.split("|") for k, v in (t.split(":"), )}

寻找二个列表中的不同元素和相同元素

list1 = [1,2,3]
list2 = [3,4,5]
set1 = set(list1)
set2 = set(list2)
print(set1 & set2) #{3}
print(set1 ^ set2) #{1, 2, 4, 5}

列表去重

l1 = ['b','c','d','c','a','a']
l2 = list(set(l1)) 

python如何实现单例模式

方法一:装饰器

def singleton(cls): 
	instances = {} 
	def wrapper(*args, **kwargs): 
		if cls not in instances: 
			instances[cls] = cls(*args,**kwargs)
		return instances[cls] 
	return wrapper
@singleton 
class Foo(object): 
	pass 
foo1 = Foo() 
foo2 = Foo() 
print(foo1 is foo2) # True

方法二:使用基类 New 是真正创建实例对象的方法,所以重写基类的new 方法,以此保证创建对象的时候只生成一个实例

class Singleton(object): 
	def new (cls, *args, **kwargs): 
		if not hasattr(cls, '_instance'): 
			cls._instance = super(Singleton, cls). new (cls, *args, **kwargs) 	
		return cls._instance
class Foo(Singleton):
 		pass
foo1 = Foo() 
foo2 = Foo() 
print(foo1 is foo2) # True

第三种:元类 元类是用于创建类对象的类,类对象创建实例对象时一定要调用call方法,因此在 调用call时候保证始终只创建一个实例即可,type是python的元类

class Singleton(type):
    def __call__(cls, *args, **kwargs):
        if not hasattr(cls,'_instance'):
            cls._instance = super(Singleton, cls).__call__ (*args, **kwargs)
        return cls._instance
# Python3
class Foo(metaclass=Singleton):
    pass
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2) # True

遍历目录与子目录

方法一:

import os
def get_files(dir,suffix):
    res = []
    for root,dirs,files in os.walk(dir):
        for filename in files:
            name,suf =os.path.splitext(filename)
            if suf == suffix:
                res.append(os.path.join(root,filename))
    print(res)
get_files("./",'.txt')

方法二:

import os
def pick(obj):
    if obj.endswith(".txt"):
        print(obj)
def scan_path(ph):
    file_list =os.listdir(ph)
    for obj in file_list:
        if os.path.isfile(obj):
            pick(obj)
        elif os.path.isdir(obj):
            scan_path(obj)
if __name__ == '__main__':
    path = input('输入目录:')
    scan_path(path)

第三种方法:


from glob import iglob
def func(fp, postfix):
    for i in iglob(f"{fp}/**/*{postfix}", recursive=True):
        print(i)
if __name__ == '__main__':
    postfix = ".txt"
    func("目录名", postfix)

列表遍历时删除元素的正确操作

a = [1,2,3,4,5,6,7,8]
for i in a[:]:
    if i%2==0:
        a.remove(i)
print(a) #[1, 3, 5, 7]

字符串转数字(不用atoi函数)

from functools import reduce 
def atoi(s): 
    return reduce(lambda num, v: num * 10 + ord(v) - ord('0'), s,0)
print(atoi("123")) #123a