一、簡介
如果你用過C或者C++,你該知道你的許多工作集中在實現數據結構上面。你需要管理內存分配,部署內存結構等等。這些東西比較乏味,通常會讓你無法集中在真正想實現的目標上面。
而在Python中,許多這種乏味的工作都去去除了。Python提供了強大的對象類型作為Python語言的一部分,解決問題時,你不需要手工寫代碼來實現這些結構了。而且你也不需要親自實現自己的數據類型。因為內置對象類型有很多好處。如果你是一個編程大牛,哪另當別論,對于初學者,我們首先需要知道如何使用。
Python內置數據類型:可以使用dir()查看數據類型支持的屬性和方法
Numbers
Strings
Lists
Dictionaries
Tuples
Files
Other types Sets,type,None,Boolean
二、Numbers
支持的number類型
Literal Interpretion |
1234,-24,0 Normal intergers(C lons)
999999999999L Long intergers(unlimited size)
1.23,3.14e-10,4E210 Floating-point numbers(C doubles)
0177,0x9ff,0xff Octal and hex literals for intergers
3+4j,3.0+4.0j,3J Comples number literals
Python expression operators and precedure
Operators Description |
yield x Generator function send protocol
lambda args:expression Anonymous function generation
x if y else z Ternary(三元的) selection expression
x or y Logical OR (X 為假才比較Y)
x and y Logical AND (X 為真才比較Y)
not x Logical negation
<,<=,>,>=,==,!=,x is y,x is not y,x not in y
x | y 按位或
x ^ y 按位異或
x & y 按位與
x << y, x>>y 按位左移,右移
-x + y, x – y 加、減
x * y, x % y, x /y, x // y 乘除
-x ,+x, ~x, x ** y
#一些操作 In [1]: 01,010,0100 Out[1]: (1, 8, 64) In [2]: 0x01,0x10,0xff Out[2]: (1, 16, 255) In [3]: oct(64),hex(64),hex(255) Out[3]: ('0100', '0x40', '0xff') In [4]: int('0100'),int('0100',8),int('0x40',16) Out[4]: (100, 64, 64)
關于number方面,math模塊有許多處理的函數。
三、Strings
1、String也叫seqeunce,字符串在Python中很容易使用,但是最復雜的地方可能在于有很多種方式編寫字符串
Single: quotes : 'spa"m'
Double quotes : "spa'm"
Triple quotes : """…pam…"",'''…spam…'''
Escape sequence : "S\tp\na\Om"
Raw strings : r"C:\new\test.spm"
Unicode strings : u"eggs\u0020spam"
2、轉義字符
Escape Sequence |
Meaning |
\newline |
Ignored |
\\ |
Backslash (\) |
\' |
Single quote (') |
\" |
Double quote (") |
\a |
ASCII Bell (BEL) |
\b |
ASCII Backspace (BS) |
\f |
ASCII Formfeed (FF) |
\n |
ASCII Linefeed (LF) |
\r |
ASCII Carriage Return (CR) |
\t |
ASCII Horizontal Tab (TAB) |
\v |
ASCII Vertical Tab (VT) |
\ooo |
ASCII character with octal value ooo |
\xhh… |
ASCII character with hex value hh… |
3、基礎操作
In [1]: a = 'abc' In [2]: 'abc' + 'def' Out[2]: 'abcdef' In [3]: 'abc' * 3 Out[3]: 'abcabcabc' In [5]: a[1] Out[5]: 'b' In [6]: a[1:2] Out[6]: 'b' In [7]: a[1:3] Out[7]: 'bc' In [8]: a[-1] Out[8]: 'c' In [9]: a[::2] Out[9]: 'ac'
4、格式化字符串
In [10]: "%d %s %d you" % (1,'spam',4)
Out[10]: '1 spam 4 you'
Format Symbol |
Conversion |
%c |
character |
%s |
string conversion via str() prior to formatting |
%i |
signed decimal integer |
%d |
signed decimal integer |
%u |
unsigned decimal integer |
%o |
octal integer |
%x |
hexadecimal integer (lowercase letters) |
%X |
hexadecimal integer (UPPERcase letters) |
%e |
exponential notation (with lowercase 'e') |
%E |
exponential notation (with UPPERcase 'E') |
%f |
floating point real number |
%g |
the shorter of %f and %e |
%G |
the shorter of %f and %E |
5、字符串的方法
'capitalize', #首字母大寫 'center', # S.center(width[, fillchar]) -> string 'count', # S.count(sub[, start[, end]]) -> int 'decode', #解碼 'encode', #編碼 'endswith', #以什么結束 'expandtabs', # S.expandtabs([tabsize]) -> string #把制表符換為多少字符 'find', # S.find(sub [,start [,end]]) -> int 'format', # 參考:http://blog.csdn.net/handsomekang/article/details/9183303 'index', #和find功能一樣,只不過找不到會報錯 'isalnum', #是否為數字,字母組成 'isalpha', #是否為字母 'isdigit', #是否為數字 'islower', #是否為小寫 'isspace', #是否為空格符 'istitle', #是否為標題樣式,即每個單詞首字母大寫 'isupper', #是否為大寫 'join', # In [33]: a = "yunzhonghe"; b = " ";b.join(a) ;Out:'y u n z h o n g h e' 'ljust', # S.ljust(width[, fillchar]) -> string 在右邊加空格 'lower', #轉變字符串為小寫 'lstrip', #去掉左邊的空格 'partition', #S.partition(sep) -> (head, sep, tail) ,分成三段 'replace', # S.replace(old, new[, count]) -> string 'rfind', #從后面往前找,功能和find一樣 'rindex', #同上,找不到會報錯 'rjust', #在左邊加空格 'rpartition', #從后往前找 'rsplit', # S.rsplit([sep [,maxsplit]]) -> list of strings 'rstrip', #限制右邊的空格 'split', # S.split([sep [,maxsplit]]) -> list of strings 以誰為分隔符 'splitlines', #返回行的列表 'startswith', #以誰開始 'strip', #去除兩邊的空格符 'swapcase', #大寫小互換 'title', #轉換為Title 樣式 'translate', # S.translate(table [,deletechars]) -> string 'upper', #轉換為大寫 'zfill' #以 0 填充字符In [58]: a.zfill(10);Out[58]: '0000000abc'
四、Lists
Lists是:有序的對象收集,通過偏移量訪問,可變長度,自由嵌套,改變sequence。
1、基礎操作
In [1]: l = ["abc",'def','ghi'] In [2]: l*3 Out[2]: ['abc', 'def', 'ghi', 'abc', 'def', 'ghi', 'abc', 'def', 'ghi'] In [3]: [l] * 3 Out[3]: [['abc', 'def', 'ghi'], ['abc', 'def', 'ghi'], ['abc', 'def', 'ghi']] In [4]: l + ["xyz"] Out[4]: ['abc', 'def', 'ghi', 'xyz'] In [5]: l[1] Out[5]: 'def' In [6]: l[1][1] Out[6]: 'e' In [7]: l[0:2] Out[7]: ['abc', 'def'] In [8]: l1 = [x**2 for x in range(5)] In [9]: l1 Out[9]: [0, 1, 4, 9, 16]
2、List 方法
'append', #添加一個元素 'count', #計算某元素出現次數 'extend', #添加大量元素 'index', # L.index(value, [start, [stop]]) -> integer -- return first index of value. 'insert', # L.insert(index, object) -- insert object before index 'pop', #取出某個數據 'remove', #刪除某個數據 'reverse', #順序翻轉 'sort' #整理順序
五、Dictionaries
Dictionaries也是非常靈活的內置數據類型,列表可以看做有序的對象收集器,Dictionary則是無序的收集。item通過key取出,而不是通過偏移量。
In [19]: dir(dict) Out[19]: '__class__', '__cmp__', '__contains__', '__delattr__', #刪除attr '__delitem__', #刪除item '__doc__', #注釋文檔信息 '__eq__', #等于 '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', #大于 '__hash__', '__init__', '__iter__', '__le__', #小于等于 '__len__', #key的個數 '__lt__', #小于 '__ne__', #不等于 '__new__', # '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', #清空字典 'copy', # D.copy() -> a shallow copy of D 'fromkeys', # In [11]: dict.fromkeys("yun","test")Out[11]: {'n': 'test', 'u': 'test', 'y': 'test'} 'get', # D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. 'has_key', # D.has_key(k) -> True if D has a key k, else False 'items', # D.items() -> list of D's (key, value) pairs, as 2-tuples 'iteritems', # D.iteritems() -> an iterator over the (key, value) items of D 'iterkeys', # 'itervalues', # 'keys', # D.keys() -> list of D's keys 'pop', # D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 'popitem', #隨意取一些key-item 數據 'setdefault', # D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D 'update', # D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] 'values', # D.values() -> list of D's values 'viewitems', # #In [30]: a.viewitems() #Out[30]: dict_items([('age', 19), ('name', 'yunzhonghe'), ('school', 'hqu')]) 'viewkeys', 'viewvalues'
六、Tuples
Tuple和List類似,都是類型收集,但是Tuple不能按位修改。
Tuple的特點:有序的收集任意對象,通過偏移量訪問,不可變sequence,固定長度,自由嵌套。
In [39]: dir(tuple) Out[39]: ['__add__', #可以和Tuple相加 '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', #占用內存的大小 '__str__', #可以調用str 方法 '__subclasshook__', 'count', #計算某個value出現多少次 'index'] #查看某value的index
七、Files
文件是一個命名的隔離存儲空間,被操作系統管理。
fp = open("test.txt",w) 直接打開一個文件,如果文件不存在則創建文件
1、open 模式:
w 以寫方式打開,
a 以追加模式打開 (從 EOF 開始, 必要時創建新文件)
r+ 以讀寫模式打開
w+ 以讀寫模式打開 (參見 w )
a+ 以讀寫模式打開 (參見 a )
rb 以二進制讀模式打開
wb 以二進制寫模式打開 (參見 w )
ab 以二進制追加模式打開 (參見 a )
rb+ 以二進制讀寫模式打開 (參見 r+ )
wb+ 以二進制讀寫模式打開 (參見 w+ )
ab+ 以二進制讀寫模式打開 (參見 a+ )
2、文件方法
fp.read([size]) #size為讀取的長度,以byte為單位 fp.readline([size]) #讀一行,如果定義了size,有可能返回的只是一行的一部分 fp.readlines([size]) #把文件每一行作為一個list的一個成員,并返回這個list。其實它的內部是通過循環調用readline()來實現的。如果提供size參數,size是表示讀取內容的總長,也就是說可能只讀到文件的一部分。 fp.write(str) #把str寫到文件中,write()并不會在str后加上一個換行符 fp.writelines(seq) #把seq的內容全部寫到文件中(多行一次性寫入)。這個函數也只是忠實地寫入,不會在每行后面加上任何東西。 fp.close() #關閉文件。python會在一個文件不用后自動關閉文件,不過這一功能沒有保證,最好還是養成自己關閉的習慣。 如果一個文件在關閉后還對其進行操作會產生ValueError fp.flush() #把緩沖區的內容寫入硬盤 fp.fileno() #返回一個長整型的”文件標簽“ fp.isatty() #文件是否是一個終端設備文件(unix系統中的) fp.tell() #返回文件操作標記的當前位置,以文件的開頭為原點 fp.next() #返回下一行,并將文件操作標記位移到下一行。把一個file用于for … in file這樣的語句時,就是調用next()函數來實現遍歷的。 fp.seek(offset[,whence]) #將文件打操作標記移到offset的位置。這個offset一般是相對于文件的開頭來計算的,一般為正數。但如果提供了whence參數就不一定 了,whence可以為0表示從頭開始計算,1表示以當前位置為原點計算。2表示以文件末尾為原點進行計算。需要注意,如果文件以a或a+的模式打開,每 次進行寫操作時,文件操作標記會自動返回到文件末尾。 fp.truncate([size]) #把文件裁成規定的大小,默認的是裁到當前文件操作標記的位置。如果size比文件的大小還要大,依據系統的不同可能是不改變文件,也可能是用0把文件補到相應的大小,也可能是以一些隨機的內容加上去。
八、后記
1、Python常用基礎類型差不多就這么多,供以后參考使用。
2、為什么表格這么大
參考:http://www.cnblogs.com/rollenholt/archive/2012/04/23/2466179.html
原創文章,作者:艾賀,如若轉載,請注明出處:http://www.www58058.com/9215
沒有上次提交的文章質量高哦。
@stanley:恩,不光供自己參考,還要讓別看看起來好才行。