如下代碼示例用的是ipython,一個比官方解釋器好不少的解釋器,值的學習和使用。python
In [18]: abs(3.14) Out[18]: 3.14 In [19]: abs(-3.14) Out[19]: 3.14
In [135]: complex(1,3)
Out[135]: (1+3j)
In [143]: divmod(12, 7)
Out[143]: (1, 5)
In [157]: max([(1,2,3), (4,5,6), (23,4,1,)], key=lambda a: a[-1]) Out[157]: (4, 5, 6) In [158]: max(1,2,3,4,4,5) Out[158]: 5 In [159]: max([(1,2,3), (4,5,6), (23,4,1,)]) Out[159]: (23, 4, 1) In [160]: max([(1,2,3), (4,5,6), (23,4,1,)], key=lambda a: a[-1]) Out[160]: (4, 5, 6) In [161]: max([{'age':10, 'name': 'aaa'}, {'age': 12, 'name': 'bb'}], key=lambda a: a['age']) Out[161]: {'age': 12, 'name': 'bb'}
In [166]: pow(2,3) Out[166]: 8 In [167]: pow(2,3,5) Out[167]: 3
In [170]: round(3.45) Out[170]: 3.0 In [171]: round(3.55) Out[171]: 4.0 In [172]: round(3.55345, 3) Out[172]: 3.553
In [175]: sum([1,2,3,4])
Out[175]: 10
In [204]: print bin(20), hex(16), oct(9) 0b10100 0x10 011
In [184]: print bool(3), bool('a') True True In [185]: print bool(0), bool(''), bool(None) False False False
In [188]: chr(320) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-188-5b2996ffe50c> in <module>() ----> 1 chr(320) ValueError: chr() arg not in range(256) In [189]: chr(65) Out[189]: 'A' In [190]: chr(0) Out[190]: '\x00'
In [225]: unichr(1245) Out[225]: u'\u04dd'
In [192]: ord('a') Out[192]: 97 In [193]: ord('\x23') Out[193]: 35
In [196]: print float('13'), float(13) 13.0 13.0 In [197]: print int('14'), int(14) 14 14 In [198]: print long('15'), long(15) 15 15
In [212]: format(123, '05d') Out[212]: '00123'
以上等同於 print ‘%05d’ % 123git
In [218]: hash(123) Out[218]: 123 In [219]: hash('abc') Out[219]: 1453079729188098211
In [221]: str(123) Out[221]: '123' In [222]: str([1,2,3]) Out[222]: '[1, 2, 3]' In [223]: str({'a': 1, 'b': 2}) Out[223]: "{'a': 1, 'b': 2}"
In [251]: file('abc.txt', 'w') Out[251]: <open file 'abc.txt', mode 'w' at 0x7f93e727a660> In [252]: open('abc.txt', 'w') Out[252]: <open file 'abc.txt', mode 'w' at 0x7f93e727a780>
In [253]: input('pls input a number >>') pls input a number >>123 Out[253]: 123
In [255]: all([1,2,3,4]) Out[255]: True In [256]: all([1,2,3,4, 0]) Out[256]: False In [257]: any([1,2,3,4, 0]) Out[257]: True
In [261]: for i, value in enumerate(['a', 'b', 'c']): .....: print i, value .....: 0 a 1 b 2 c
In [263]: filter(lambda x: x>3, [1,2,3,4,5]) Out[263]: [4, 5]
讀取文件的時候比較有用:數據結構
with open("mydata.txt") as fp: for line in iter(fp.readline, "STOP"): process_line(line)
In [267]: len('abc'), len([1,2,3]) Out[267]: (3, 3)
In [269]: map(lambda x: x+3, [1,2,3]) Out[269]: [4, 5, 6] In [270]: a = [1,2]; b = ['a', 'b']; c = ('x', 'y') In [271]: map(None, a, b, c) Out[271]: [(1, 'a', 'x'), (2, 'b', 'y')]
In [281]: reduce(lambda a, b: a-b, [1,2,3]) Out[281]: -4
In [283]: zip([1,2,3], ('a', 'b', 'c')) Out[283]: [(1, 'a'), (2, 'b'), (3, 'c')]
In [274]: [x for x in xrange(10)] Out[274]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [275]: [x for x in xrange(5, 10)] Out[275]: [5, 6, 7, 8, 9] In [276]: [x for x in xrange(5, 10, 2)] Out[276]: [5, 7, 9] In [277]: range(10) Out[277]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [278]: range(5, 10) Out[278]: [5, 6, 7, 8, 9] In [279]: range(5, 10, 2) Out[279]: [5, 7, 9]
可選參數cmp、key和reverse與list.sort()方法的參數含義相同(在可變的序列類型一節描述)。
cmp指定一個自定義的帶有兩個參數的比較函數(可迭代的元素),它應該根據第一個參數是小於、等於仍是大於第二個參數返回負數、零或者正數:cmp=lambda x,y: cmp(x.lower(), y.lower())。默認值是None。
key指定一個帶有一個參數的函數,它用於從每一個列表元素選擇一個比較的關鍵字:key=str.lower。默認值是None(直接比較元素)。
reverse是一個布爾值。若是設置爲True,那麼列表元素以反向比較排序。
一般狀況下,key和reverse轉換處理比指定一個等同的cmp函數要快得多。這是由於cmp爲每一個元素調用屢次可是key和reverse只會觸摸每一個元素一次。使用functools.cmp_to_key()來轉換舊式的cmp函數爲key函數。app
In [288]: sorted(d.items(), key=lambda a: a[1]) Out[288]: [('a', 3), ('b', 4)] In [289]: sorted(d.items(), key=lambda a: a[1], rev) In [289]: sorted(d.items(), key=lambda a: a[1], reverse=True) Out[289]: [('b', 4), ('a', 3)] In [290]: sorted(d.items(), cmp=lambda a, b: cmp(a[1], b[1])) Out[290]: [('a', 3), ('b', 4)]
bytearray() dict() frozenset() list() set() tuple()
python裏面經常使用的數據結構有列表(list)、字典(dict)、集合(set)、元組(tuple)ide
如下是一些類(class)和類型相關的函數,比較不經常使用,能夠查看手冊詳細瞭解。
basestring() callable() classmethod() staticmethod() property() cmp() compile() delattr() getattr() setattr() hasattr() dir() globals() locals() vars() help() id() isinstance() issubclass() object() memoryview() repr() super() type() unicode() import() eval() execfile()函數
apply() buffer() coerce() intern()學習
ipython是一個很是好的交互式python解釋器,它查看一個函數或類的用法的方法有:ui
In [292]: import time In [293]: time. time.accept2dyear time.clock time.gmtime time.sleep time.struct_time time.tzname time.altzone time.ctime time.localtime time.strftime time.time time.tzset time.asctime time.daylight time.mktime time.strptime time.timezone In [293]: time.ti time.time time.timezone In [293]: time.time? Docstring: time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. Type: builtin_function_or_method
文章來源於python學習筆記:www.yuanrenxue.comspa