时间:2021.05.27
环境:Windows
目的:Python实例若干条
说明:
作者:Zhong QQ交流群:121160124 欢迎加入!
目录
列表推导式
print([i for i in range(1, 10)])
数组去重
ls = ['a', 1, 2, 1, 'a']
print(list(set(ls)))
运行计时器
base64编解码
import base64
test_str = "Hello"
# 编码
encode_str = base64.encodebytes(test_str.encode()) # b'SGVsbG8=\n'
print(encode_str)
print(encode_str.decode()) # 默认以utf8解码
# 解码
decode_str = base64.decodebytes(encode_str)
print(decode_str) # b'Hello'
print(decode_str.decode()) # 默认以utf8解码,结果 Hello
字典推导式
annotate = [{"category_name":"科技", "count": 1}, {"category_name":"农业", "count": 2}]
_dict = {i["category_name"]:i["count"] for i in annotate}
print(_dict)
回调
class T1():
def t1(self, func):
print(1)
self.callback = func()
print(2)
def callback(self):
print("回调")
def func():
print('he')
t1 = T1()
t1.t1(func)
map结合lambda获取字段内容
profile = {"name":"a", "age":18}
name, age, gender = map(lambda x: profile.get(x, None), ("name", "age", "gender"))
print(name)
print(age)
print(gender)
指定位数字符串全排列
A = 'ABCDEF'
# 方法一:
from itertools import product
print(list(product(A, repeat=2)))
# 方法二:
print([x + y for x in A for y in A])
# 方法三
def pro(strings, repeat=2):
pools = [strings] * repeat
result = [""]
for pool in pools:
ls = []
for x in result:
for y in pool:
ls.append(x + y)
# result = [x + y for x in result for y in pool]
result = ls
print(result)
pro(A, 2)
关注微信公众号 如果对你有帮助请多多支持