Python基礎—內置數據類型

一、簡介      

       如果你用過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

1String也叫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

TupleList類似,都是類型收集,但是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)     直接打開一個文件,如果文件不存在則創建文件

 

1open 模式:

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

(0)
艾賀艾賀
上一篇 2015-11-10 22:36
下一篇 2015-11-10 22:40

相關推薦

  • Linux的用戶,組及文件權限管理

    Linux用戶與組的創建,刪除,屬性修改,文件權限管理

    Linux干貨 2018-02-24
  • 自己做一個CA

    構建CA服務器    CA配置文件位置:        /etc/pki/tls/openssl.cfg           &n…

    Linux干貨 2017-04-11
  • 邏輯卷實戰演練

    1、創建一個至少有兩個PV組成的大小為20G的名為testvg的VG;要求PE大小為16MB, 而后在卷組中創建大小為5G的邏輯卷testlv;掛載至/users目錄 2、新建用戶archlinux,要求其家目錄為/users/archlinux,而后su切換至archlinux用戶,復制/etc/pam.d目錄至自己的家目錄 3、擴展testlv…

    Linux干貨 2016-09-01
  • N25期第四周作業

    1.復制/etc/skel目錄為/home/tuser1,要求/home/tuser1及其內部文件的屬組和其它用戶均沒有任何訪問權限 cp -r /etc/skel /home/tuser1 chmod -R go= /home/tuser1 2.編輯/etc/group文件,添加組hadoop echo “hadoop:x:1080” >> /…

    Linux干貨 2016-12-26
  • 任務計劃

    Linux 任務計劃、周期性任務執行 未來的某時間點執行一次任務 at batch :系統 自行選擇空閑時間去執行此處指定的任務 周期性運行某任務 cron [root@localhost ~]# rpm -q at (CentOS6中使用) at-3.1.10-48.el6.x86_64 [root@localhost ~]# rpm -ql at /et…

    Linux干貨 2017-05-13
  • Trap命令簡介

     Trap命令簡介     一、基本概念  trap是一個shell內建命令,它用來在腳本中指定信號如何處理。比如,按Ctrl+C會使腳本終止執行,實際上系統發送了SIGINT信號給腳本進程,SIGINT信號的默認處理方式就是退出程序。如果要在Ctrl +C不退出程序,那么就得使用trap命令來指定一下SIGINT的處…

    Linux干貨 2015-05-11

評論列表(2條)

  • stanley
    stanley 2015-11-10 22:39

    沒有上次提交的文章質量高哦。

    • 云中鶴
      云中鶴 2015-11-11 20:09

      @stanley恩,不光供自己參考,還要讓別看看起來好才行。

欧美性久久久久