1.format函数--根据关键字和位置选择性插入数据
In [11]: '{mingzi}jintian{dongzuo}'.format(mingzi='duzi',dongzuo='i love you')
Out[11]: 'duzijintiani love you'
In [12]: '{1}jintian{0}'.format('duzi','i love you')
Out[12]: 'i love youjintianduzi'
In [13]: '{0}jintian{1}'.format('duzi','i love you')
Out[13]: 'duzijintiani love you'
In [14]: '{0}jintian{0}'.format('duzi','i love you')
Out[14]: 'duzijintianduzi
2.不使用Python内置函数对列表进行排序
#-*- coding:utf-8 -*-
a = [1,4,5,6,2,8,4]
alen = len(a)
for x in xrange(1,alen):
if a[x-1] > a[x]:
a[x],a[x-1] = a[x-1],a[x]
for j in xrange(1,alen):
if a[j-1] > a[j]:
a[j],a[j-1] = a[j-1],a[j]
print a
3.python之json
json.dumps 将 Python 对象编码成 JSON 字符串
json.loads 将已编码的 JSON 字符串解码为 Python 对象
代码实例:
#语法
#json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
#ensure_encoding='utf-8' 防止中文乱码
#indent=4 缩进为4
#separators=(',',':') items之间用','分开,key:value使用':'分开
import json
data = [{'a':1,'b':2,'c':3,'d':4,'e':5}]
json_str = json.dumps(data,ensure_ascii='utf-8',sort_keys=True,indent=4,separators=(',',':'))
with open('data.json', 'w') as f:
f.write(json_str)
'''
[
{
"a":1,
"b":2,
"c":3,
"d":4,
"e":5
}
]
'''
#json.loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw
print json.loads(json_str)
#[{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}]
traceback:捕获并打印异常
import traceback try: 1/0 except Exception, e: #traceback.print_exc() #c = traceback.format_exc() #print(c) traceback.print_exc(file=open('nihao.txt','w+')) ''' traceback.print_exc()跟traceback.format_exc()有什么区别呢? format_exc()返回字符串,print_exc()则直接给打印出来。 即traceback.print_exc()与print traceback.format_exc()效果是一样的。 print_exc()还可以接受file参数直接写入到一个文件。比如 traceback.print_exc(file=open('tb.txt','w+')) 写入到tb.txt文件去。 '''
快速排序
def quicklist(list1): if len(list1) < 1: return list1 less = [] base = list1.pop() max = [] for i in list1: if i < base: less.append(i) else: max.append(i) return quicklist(less) + [base] + quicklist(max) if __name__== '__main__': lis= [1,2,6,3,4,5,9,6] a = quicklist(lis) print (a)
sort,sorted
a = [1,2,4,3,5,9,5] a.sort(reverse=True) b = a.sort(reverse=True) c =sorted(a) print b print a print c None [9, 5, 5, 4, 3, 2, 1] [1, 2, 3, 4, 5, 5, 9]