1. 逻辑判断的几种写法
a, b = 1, 2
if a > b:
c = a
else:
c = b
print(c) # 2
# 三元表达式
c = a if a > b else b
print(c) # 2
# 列表
c = [b, a][a > b]
print(c) # 2
# 元组
c = (a > b and a or b)
print(c) # 2
说明:
# 列表
c = [b, a][a > b]
c = [2, 1][1 > 2]
c = [2, 1][False]
c = [2, 1][0]
>>> False == 0
True
>>> True == 1
True
>>> [2, 1][False]
2
>>> [2, 1][True]
1
# 元组
c = (a > b and a or b)
c = (False and 1 or 2)
c = (False or 2)
2. unicode字符和中文相互转换
# 中文转unicode
a = "你的坚持终将美好"
print(a.encode('unicode-escape').decode())
# unicode字符串转中文
a = "\\u4f60\\u7684\\u575a\\u6301\\u7ec8\\u5c06\\u7f8e\\u597d"
print(a.encode().decode("unicode-escape"))
import ast
print(ast.literal_eval('["\\u4f60\\u7684\\u575a\\u6301\\u7ec8\\u5c06\\u7f8e\\u597d"]'))
3. json.dumps()中文转成unicode的问题
import json
text = "你的坚持,终将美好"
res = json.dumps(text)
print(res) # "\u4f60\u7684\u575a\u6301\uff0c\u7ec8\u5c06\u7f8e\u597d"
res = json.dumps(text, ensure_ascii=False)
print(res) # "你的坚持,终将美好"
4. 英文字母往前一位偏移加密小算法
import string
def get_previous_letter(letter_now):
"""
对字母进行上一位赋值,比如a=z,b=a,c=b,d=b
"""
letter_previous = ord(letter_now) - 1
# ord('a')=97
if letter_previous == 96:
# ord('z')=122
letter_previous = 122
# ord('A')=98
if letter_previous == 64:
# ord('Z')
letter_previous = 90
# 往后一位赋值,上面的代码需要+1
# if letter_previous == 123:
# letter_previous = 97
# if letter_previous == 91:
# letter_previous = 65
return chr(letter_previous)
def handle_str(data_str):
temp_str = ""
for str_ in str(data_str):
if str_.lower() in string.ascii_letters:
letter_previous = get_previous_letter(str_)
temp_str += letter_previous
else:
temp_str += str_
return temp_str
data = "ifmmp xpsme"
print(handle_str(data))
5. 字段取值
a = {'name':1, 'action':2}
print('%(name)s %(action)s to ' % a)
6. 单例
class Singleton(object):
__instance = None
__init_flag = True
def __init__(self):
if Singleton.__init_flag:
Singleton.__init_flag = False
print('__init__...')
def __new__(cls, *args, **kwargs):
if Singleton.__instance is None:
Singleton.__instance = object.__new__(cls, *args, **kwargs)
return Singleton.__instance
one = Singleton()
two = Singleton()
7.字典和列表排序
intervals = [[1,3],[2,6],[8,10],[15,18]]
intervals.sort(key=lambda x:x[0])
print(intervals)
dict1={'a':2,'e':3,'f':8,'d':4, 'b':3}
dict2 = sorted(dict1.items(),key=lambda x:(x[1],x[0]))
print(dict2)