sorted排序
# reverse=True反向排序
example_list = [5, 0, 6, 1, 2, 7, 3, 4]
sorted(example_list, reverse=True)
# [7, 6, 5, 4, 3, 2, 1, 0]
# 通过 key 的值来进行数组/字典的排序
array = [{"age":20,"name":"a"},{"age":25,"name":"b"},{"age":10,"name":"c"}]
array = sorted(array,key=lambda x:x["age"])
print(array)
# 多字段排序:成绩降序排序,相同成绩的按照名字升序排序
d1 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]
l = sorted(d1, key=lambda x:(-x['score'], x['name']))
print(l)
按照特定格式显示时间
import time
print (time.strftime("%H:%M:%S"))
## 12 hour format ##
print (time.strftime("%I:%M:%S"))
dict1 = {'a':1,'b':2,'c':3,'d':4}
dict2 = {'a':1,'b':2,'c':5,'e':6}
differ = set(dict1.items()) ^ set(dict2.items())
print(differ)
#所有差异
#输出:{('c', 3), ('e', 6), ('c', 5), ('d', 4)}
diff = dict1.keys() & dict2
diff_vals = [(k, dict1[k], dict2[k]) for k in diff if dict1[k] != dict2[k]]
print(diff_vals)
#相同key,不同value
#输出:[('c', 3, 5)]
a = {'a': 1, 'b':3, 'c':4}
del a['a'], a['b']
d1 = {'a': 'b', 'c': 'd'}
d2 = {'a': 'b'}
set(d2.items()).issubset(d1.items())
字典使用
字典合并 :只能有两个
dict(dict1, **dict2)
random模块&string模块
random.randint(0, 8)
suffix = random.sample(string.digits, 8) # suffix得到一个包含8个字符串的列表
string.ascii_letters #'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Python常见字符编码间的转换
获取秒级时间和毫秒级时间
int(time.time())
random.choice([1, 2, 3, 4, 5])
python 一篇搞定所有的异常处理
list.sort() == None
sorted(list) == 排序后的list
https://www.csdn.net/gather_2e/MtjaQg3sODA1LWJsb2cO0O0O.html
https://blog.csdn.net/DongGeGe214/article/details/52193360
dict1~5为包含所需要的键值对,实际上就是用join将字典中的值拼接成sql语句所需要的形式
# select
where_conditions = " AND ".join(["%s='%s'" % (key, dict1.get(key)) for key in dict1])
sql = "SELECT * FROM %s WHERE %s;" % (database_table, where_conditions)
# insert
keys = ', '.join([key for key in dict2.keys()])
values = ', '.join(["'%s'" % value for value in dict2.values()])
sql = "INSERT INTO %s (%s) VALUES (%s);" % (database_table, keys, values)
# update
set_data = ", ".join(["%s='%s'" % (key, dict3.get(key)) for key in dict3])
where_conditions = " AND ".join(["%s='%s'" % (key, dict4.get(key)) for key in dict4])
sql = "UPDATE %s SET %s WHERE %s;" % (database_table, set_data, where_conditions)
# delete
where_conditions = " AND ".join(["%s='%s'" % (key, dict5.get(key)) for key in dict5])
sql = "DELETE FROM %s WHERE %s;" % (database_table, where_conditions)
instance()认为子类是易中父类类型,考虑继承关系
type() 不会认为子类是一种父类类型,不考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()。
a = 2
isinstance (a,int) # True
isinstance (a,str) # False
isinstance (a,(str,int,list)) # True (是元组中的一个返回 True)
# 第一种
a = {'a':1, 'b':'x'}
b = {'c':2, 'd':'y'}
x = dict(a, **b)
#第二种(会覆盖掉字典a)
a.update(b)
# python3
y = {**a, **b}
dict0 = dict(dict1, **dict2)
#先pip install collections2(好像用不了)
a = {'a':1, 'b':'x'}
b = {'c':2, 'd':'y'}
c = {'e':1, 'f':'x'}
result = a.copy()
args = [b, c]
# update后,result会被改变,最后的字典内会覆盖相同的键
[result.update(item) for item in args]