日常Python代码中会经常遇到一些可以用很简短的代码即可实现的功能,不用自己去撸一个单独的函数或者多个循环语句了。其实一般主要靠Google搜索关键字即可在stackoverflow找到,只能说像我等伪程序员离开网络写代码质量会直线下降。贴到这里也是方便自己使用,代码比较基础,仅作笔记使用。
合并列表值
输入的两个数组,输出一个是数组&值相加或者相乘,原文:eg-1:
# input
first = [1,2,3,4,5]
second = [6,7,8,9,10]
#output
three = [7,9,11,13,15]
# The zip function is useful here, used with a list comprehension.
# add
[x + y for x, y in zip(first, second)]
# other
[x*y for x, y in zip(first, second)]
[max(x,y) for x, y in zip(first, second)]
其实也可以遍历列表长度,然后操作。
另外如果对一个列表进行去重,直接采用set进行操作即可:
in_list = ['1', '2', '1', '3']
in_list = list(set(in_list))
合并字典值
合并两个字典,并将相同键的值进行操作,可以利用collections中的Counter进行操作,原文:eg-2:
>>> from collections import Counter
>>> A = Counter({'a':1, 'b':2, 'c':3})
>>> B = Counter({'b':3, 'c':4, 'd':5})
>>> A + B
Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})
更多Counter的操作可以参考官网指南,collections.
json与字典转换
不管是存储到数据库还是网络接口输出,都可以采用json格式,格式非常容易操作,而dict类型在Python中也很好操作,而且还可以嵌套。
import json
data = {'a':"A",'b':(2,4),'c':3.0} # dict
data_string = json.dumps(data) # string & json
print "ENCODED:",data_string
decoded = json.loads(data_string) ## dict
print "DECODED:",decoded
多列数据表与字段
有时候插入或者更新数据的时候数据表会有很多字段,这时也可以采用dict进行操作:
people_dict = {'name':'name', 'password':'password', 'salt':'salt'} # long dict
columns = ', '.join(people_dict.keys())
placeholders = ', '.join('?' * len(people_dict))
insert_sql = 'INSERT INTO user ({}) VALUES ({})'.format(columns, placeholders)
cursor_obj.execute(insert_sql, people_dict.values())
另外数据库插入一般可以采用executemany进行操作:
in_list = [('a','1'),('b','2')]
c.executemany(""" INSERT INTO result ('name','value') values(?,?)""", in_list)
排序问题
字典根据键排序, 原文:eg-3:
>>> import collections
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> od = collections.OrderedDict(sorted(d.items()))
>>> od
>>> OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
字典根据值排序, 原文:eg-4:
>>> import operator
>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> sorted_x = sorted(x.items(), key=operator.itemgetter(1))
>>> sorted_x
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
日期操作
格式化日期与unixtimestamp的相互转换,原文:eg-5:
>>> import datetime
>>> import time
>>> dt = datetime.datetime(2010, 2, 25, 23, 23)
>>> time.mktime(dt.timetuple())
>>>
from datetime import datetime
import time
#-------------------------------------------------
# conversions to strings
#-------------------------------------------------
# datetime object to string
dt_obj = datetime(2008, 11, 10, 17, 53, 59)
date_str = dt_obj.strftime("%Y-%m-%d %H:%M:%S")
print date_str
# time tuple to string
time_tuple = (2008, 11, 12, 13, 51, 18, 2, 317, 0)
date_str = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)
print date_str
#-------------------------------------------------
# conversions to datetime objects
#-------------------------------------------------
# time tuple to datetime object
time_tuple = (2008, 11, 12, 13, 51, 18, 2, 317, 0)
dt_obj = datetime(*time_tuple[0:6])
print repr(dt_obj)
# date string to datetime object
date_str = "2008-11-10 17:53:59"
dt_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print repr(dt_obj)
# timestamp to datetime object in local time
timestamp = 1226527167.595983
dt_obj = datetime.fromtimestamp(timestamp)
print repr(dt_obj)
# timestamp to datetime object in UTC
timestamp = 1226527167.595983
dt_obj = datetime.utcfromtimestamp(timestamp)
print repr(dt_obj)
#-------------------------------------------------
# conversions to time tuples
#-------------------------------------------------
# datetime object to time tuple
dt_obj = datetime(2008, 11, 10, 17, 53, 59)
time_tuple = dt_obj.timetuple()
print repr(time_tuple)
# string to time tuple
date_str = "2008-11-10 17:53:59"
time_tuple = time.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print repr(time_tuple)
# timestamp to time tuple in UTC
timestamp = 1226527167.595983
time_tuple = time.gmtime(timestamp)
print repr(time_tuple)
# timestamp to time tuple in local time
timestamp = 1226527167.595983
time_tuple = time.localtime(timestamp)
print repr(time_tuple)
#-------------------------------------------------
# conversions to timestamps
#-------------------------------------------------
# time tuple in local time to timestamp
time_tuple = (2008, 11, 12, 13, 59, 27, 2, 317, 0)
timestamp = time.mktime(time_tuple)
print repr(timestamp)
# time tuple in utc time to timestamp
time_tuple_utc = (2008, 11, 12, 13, 59, 27, 2, 317, 0)
timestamp_utc = calendar.timegm(time_tuple_utc)
print repr(timestamp_utc)
#-------------------------------------------------
# results
#-------------------------------------------------
# 2008-11-10 17:53:59
# 2008-11-12 13:51:18
# datetime.datetime(2008, 11, 12, 13, 51, 18)
# datetime.datetime(2008, 11, 10, 17, 53, 59)
# datetime.datetime(2008, 11, 12, 13, 59, 27, 595983)
# datetime.datetime(2008, 11, 12, 21, 59, 27, 595983)
# (2008, 11, 10, 17, 53, 59, 0, 315, -1)
# (2008, 11, 10, 17, 53, 59, 0, 315, -1)
# (2008, 11, 12, 21, 59, 27, 2, 317, 0)
# (2008, 11, 12, 13, 59, 27, 2, 317, 0)
# 1226527167.0
# 1226498367
一些输出格式
输出的时候如果采用“\t”进行格式化,也会出现一些对齐问题,可以采用”\t”和“%-20s”格式化代码:
# 20 could be change to another value
print "\t%-20s%-20s%-20s%-20s%-20s%-20s"% tuple(in_list)
todo
未完待续