好玩的小方法积累区, 可以跟我补充呀~
开头唠叨两句
有啥好玩的方法可以告诉我,积累一些小代码断
Author: Leo
Wechat: Leo-sunhailin
QQ: 379978424
E-mail: 379978424@qq.com
现在有12345五个东西,求分成2,3,4,5组的全排列总和,且每组每个方法不能重复。
1 2 3 4 for i in range(2 , 6 ): for j in itertools.permutations('12345' , i): print([int(x) for x in j])
一般网页请求json数据返回的json到了Python中会变为字典形式,但是Python(3.6还是3.5之前)的字典是无序的,如果业务需求要有序的话,只要做如下修改:
1 2 3 4 5 6 7 8 from collection import OrderedDictresult = urllib.request.urlopen(url).read().decode("UTF-8" ) json_result = json.loads(result, object_pairs_hook=OrderedDict)
如果你的MongoDB数据库中存了类似于这样的数据 LUUID(“e5e1c8ee-cb58-11e7-a088-f82819e1bcfa”), 实际上就UUID类型的数据,这时候改怎么读取回来之后查询呢?
官方文档: 官方文档
在讲如何查询之前先说明一下查询回来的结果只有 e5e1c8ee-cb58-11e7-a088-f82819e1bcfa 这一段,而且不能用
find({“xxx”: “e5e1c8ee-cb58-11e7-a088-f82819e1bcfa”})
或者
find({“xxx”: “LUUID(“e5e1c8ee-cb58-11e7-a088-f82819e1bcfa”)”})
结果都是无法查询到的
接下来先要明白的是MongoDB实际上存储的是一种叫做bson的类json数据格式(可以互换).所以方向有了接下来就是查询BSON里面对于UUID的定义了.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 from bson import UUIDLegacyfrom bson.binary import UUIDquery = {"xxx" : UUIDLegacy(UUID(<你的字符串类型的uuid>))} conn = ... db = conn[<表名>] col = db[<集合名>] col.find(query) ...
求两个List的差集和交集和并集
1 2 3 4 5 6 7 8 9 10 11 12 13 14 list_1 = [2 , 7 , 0 , 1 , 6 , 5 ] list_2 = [2 , 7 , 0 ] diff_set = [i for i in list_1 if i not in list_2] public = [i for i in list_1 if i in list_2] union = list(set(list_1).union(set(list_2)))
将一个列矩阵转换为对角矩阵
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 if __name__ == '__main__' : def fill (data, pos, max_length) : if isinstance(data, list): data = data[0 ] a = [0 ] * (max_length - 1 ) a.insert(pos, data) yield a test = [1 , 2 , 3 , 4 ] res = [fill(d, i, max_length=len(test)).__next__() for i, d in enumerate(test)] print(res)
斐波那契数列的简化写法
1 2 3 4 5 6 7 8 9 10 11 12 def fibonacci (a, b, max_value) : while True : a, b = b, a+b if max_value != (b > max_value and b or max_value): break yield b if __name__ == '__main__' : res = [1 , 1 ] + [num for num in fibonacci(a=1 , b=1 , max_value=10 )] print(res)
等分List(有奇偶处理逻辑)
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 def i_split_by_n (ls, n) : for i in range(0 , len(ls), n): yield ls[i:i+n] def split_by_n (ls, group) : """ 等分List(有奇偶处理逻辑) 逻辑: 将多出的部分和倒数第二组进行合并 :param ls: 需要等分的list :param group: 组数 :return: 返回划分结果 """ res = list(i_split_by_n(ls, int(len(ls) / group))) if len(res) != group: res = res[:-2 ] + [res[-2 ] + res[-1 ]] return res if __name__ == '__main__' : list_test = [x for x in range(1 , 14 )] print(list_test) print(split_by_n(ls=list_test, group=3 ))