python问题记录1

排序:

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']

 

判断一个dict是另一个dict的子集

d1 = {'a': 'b', 'c': 'd'}
d2 = {'a': 'b'}
set(d2.items()).issubset(d1.items())

获取当前函数名

https://www.cnblogs.com/yoyoketang/p/9231320.html

字典的使用:

字典使用

字典合并 :只能有两个

dict(dict1, **dict2)

random使用:

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函数执行超时后跳过

python笔记19-获取当前运行函数名称和类方法名称(可能会用到)

异常处理

python 一篇搞定所有的异常处理

python2,3的不同

  1. 列表.sort() == None
  2. cmp()比较列表的函数在python3中没有了
  3.  

比较列表:

list.sort() == None

sorted(list) == 排序后的list

设置跨文件全局变量

 

python 如何去掉u

https://www.csdn.net/gather_2e/MtjaQg3sODA1LWJsb2cO0O0O.html

新建字典

https://blog.csdn.net/DongGeGe214/article/details/52193360

拼接sql语句

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]

 

你可能感兴趣的:(python)