Python Notes

1. format of strings

'{dog} is called {name}'.format(dog='doggy', name='jk')
# output: 'doggy' is called jk


2. 

>>> print '\101'  #oct
A
>>> print '\x41'
A


3. sort the list

>>> b = [[1, 2], [4, 1], [5, 2], [-1, 4]]
>>> b
[[1, 2], [4, 1], [5, 2], [-1, 4]]
>>> b.sort(key=lambda x:x[1])  #here x refers to each element of list b. Obviously x is also a list. Sorting according to x[1]'s value
>>> b
[[4, 1], [1, 2], [5, 2], [-1, 4]]
>>> b.sort(key=lambda x:x[0])
>>> b
[[-1, 4], [1, 2], [4, 1], [5, 2]]


4. Deep Copy in python

Note: the following can just deep copy the top level of the elements. As to the lower structure inside the list and dcit, only the references will be copied.

>>> L = [1, 2, 3]
>>> A = L[:]  #deep copy
>>> A
[1, 2, 3]
>>> A[2] = 'jkk'
>>> A
[1, 2, 'jkk']
>>> D = {'a': 2, 'b': 1}
>>> B = D.copy()
>>> B['2'] = 3
>>> D
{'a': 2, 'b': 1}
>>> B
{'a': 2, '2': 3, 'b': 1}

5. Complete Deep Copy

import copy
b = copy.deepcopy(a) # deep copy of all level structure

6 try catch, error print and traceback

def catchError():
    try:
        a = 3/0
    except Exception as e:
        logging.traceback.print_exc()

7. output content into a file

>>> print >> open("a.txt", "w"), "HE"*100
# write the string content into a.txt file






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值