python核心基礎縱覽(上)

keithl發表於2017-10-09

Number型別

整數與浮點數

## python2.7 
a = 123848488483993932002093939L        ## 要加L,py2.7有長整型
b = 23.03
c = 10 / 4      ## 2
d = 10 / 4.0    ## 2.5
e = 10 // 4     ## 2
f = 10 // 4.0   ## 2.0

## python3.5
a = 1238484884839939320020939393839303  ## 不需要加L,python3.x是屬於單個整數型別,不區分長整型
b = 29.90
c = 10 / 4      ## 2.5
d = 10 / 4.0    ## 2.5
e = 10 // 4     ## 2
f = 10 // 4.0   ## 2.0複製程式碼

Boolean,只有兩個值:True && False

a = False
b = True複製程式碼

十進位制轉16進位制、8進位制、2進位制

num = 29  ## 10進位制
## 轉16進位制
hex(num)   ## 0x1d

## 轉8進位制
oct(num)   ## 0o35

## 轉2進位制
bin(num)   ## 0b11101複製程式碼

16進位制、8進位制、2進位制轉十進位制

## 16進位制轉10進位制
str_hex = r'0x1d'
int(str_hex,base = 16)

## 8進位制轉10進位制
str_oct = r'0o35'
int(str_oct,base = 8)

## 2進位制轉10進位制
str_bin = r'0b11101'
int(str_bin,base = 2)複製程式碼

Sequence型別簇

序列型別簇

  • 字串String
  • 元組Tuple
  • 列表List

基本操作符

  • A[index]:獲取序列第index個元素,index取值從0開始
  • A[index1:index2]:切片操作,獲取序列中index1到index2-1的子序列
  • A in B:判斷序列B是否有A,如果有返回True,否則返回False
  • A not in B:判斷序列B是否沒有A,如果沒有返回True,否則返回False
  • A + B :將序列A和序列B合併並組成一個新的序列返回
  • A * number :將序列A重複拼接number次並將拼接後新組成的序列返回
  • A == B:序列A與序列B的值和長度都相等

序列比較cmp原理(A > B or A < B)

  • 如果比較的元素是同型別的,則比較其值,返回結果。
  • 如果兩個元素不是同一種型別,則檢查它們是否是數字。
    • 如果是數字,執行必要的數字強制型別轉換,然後比較。
    • 如果有一方的元素是數字,則另一方的元素"大"(數字是"最小的")
    • 否則,通過型別名字的字母順序進行比較。
  • 如果有一個列表首先到達末尾,則另一個長一點的列表"大"。
  • 如果我們用盡了兩個列表的元素而且所 有元素都是相等的,那麼結果就是個平局,就是說返回一個 0

String型別

String是由零個或者多個字元組成的有限序列,通常以串的整體作為操作物件,字串以引號包含標識

## 字串定義
a = 'single'                ## 單引號表示
b = "double"                ## 雙引號表示
c = """...spam..."""        ## 三引號表示
d = '''...spam...'''        ## 三引號表示

e = "s\tp\na\0m"            ## 轉義序列
f = r"C:\new\test.spm"      ## raw 字串,即用r禁用轉義字元
bs = b'sp\x01am'            ## 位元組字串
us = u"中文"                ## Unicode字串複製程式碼

==如果字串包含中文,應當宣告為unicode字串==

字串格式化表示式

## 格式化表示式:"...%s..." % (values) Or "...%(keyname)s..." % {keyname:keyvalue}
>>> "this is my %s" % ('name')
'this is my name'

>>> "this is my %(name)s" % {'name':'xiao'}
'this is my xiao'

## 格式化方法呼叫:"...{}...".format(values) Or "...{keyname1}...".format(keyname1=value1)
>>> "my name is {}".format('xiaokunliu')
'my name is xiaokunliu'

>>> "this is my {firstname},and {lastname}".format(firstname="xiaokun",lastname="liu")
'this is my xiaokun,and liu'複製程式碼

字串格式化結構:%[(keyname)][flags][width][.precision]typecode

## keyname:字典對應索引的keyname
>>> '%(name)s' % {'name':'xiaokun'}
'xiaokun'

##  flags:格式化符號(-、+、space空格鍵<sp>、#、0、m.n)
##  -:左對齊;
##  +:對正數輸出正值符號;
##  m.n:m是顯示最小總寬度,n是小數點後的位數;
##  #:在8進位制數前面顯示0,16進位制前面顯示"0x"或者"0X"
##   0:數字大小不足m.n的要求時用0補位;
##   <sp>:數字大小不足m.n的要求時用空格補位;
x = 1.23456789
>>> "%-6.2f,%+3.4f,%#2.3f,%06.9f,% 3.9f" % (x,x,x,x,x)
'1.23  ,+1.2346,1.235,1.234567890, 1.234567890'

## width:指定顯示字串的寬度
>>> '%−6.2f' % x
'1.23  '
'
## .precision:整數格式化為字串的時候需要保留的小數位數
>>> '%.3f' % x
'1.235'

## typecode:格式化符號
%s      String (or any object’sstr(X)string) 
%r      Same ass, but usesrepr, not str 
%c      Character (int or str)
%d      Decimal (base-10 integer)
%i      Integer
%u      Same asd(obsolete: no longer unsigned) 
%o      Octal integer (base 8)
%x      Hex integer (base 16)
%X      Same asx, but with uppercase letters
%e      Floating point with exponent, lowercase 
%E      Same ase, but uses uppercase letters
%f      Floating-point decimal
%F      Same asf, but uses uppercase letters
%g      Floating-point e or f
%G      Floating-point E or F
%%      Literal%(coded as%%)複製程式碼

Tuple型別

定義

  • 用圓括號表示,在不同元素之間以逗號隔開
  • Tuple大小以及其中的元素在初始化後不能修改
  • Tuple比可修改的List操作速度快
  • 用途;可以用於定義一組常量集並用於不斷讀取

簡單示例

## 定義
>>> tuple1 = ('you',283,93,'English',4,5.6)

## 讀取
>>> tuple1[3]

## 擷取子元組
>>> subTuple = tuple1[3:]

## 可以對元組變數重新賦值,注意是元組變數不是元組物件
>>> tuple1 = tuple1 + (2,3,'playing')

## 獲取長度
>>> len(tuple1)

## 不能修改
>>> tuple1[2] = "update"    ### 這裡將發生錯誤
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

## 元素可重複
>>> tuple1 = tuple1 * 2複製程式碼

List型別

定義

  • 使用中括號表示,即[],不同元素之間以逗號隔開
  • List大小和其中的元素在初始化後可以被再次修改
  • 用途:對於定義的一組資料集,要求能夠進行增刪改查操作

簡單示例

## 定義
>>> color_list = ['green','red','pink','blue','black','white']

## 讀取元素
>>> color_list[2]

## 擷取子列表
>>> color_list[3:]

## 修改指定序列的內容
>>> color_list[2] = "update_pink"

## 獲取長度
>>> len(color_list)

## 元素遍歷
>>> for color in color_list:
...     print color
...

## 排序,排序後本身的color_list不變
>>> sorted_color_list = sorted(color_list)

## 求和
>>> num_list = [3.4,5,6,3,5.7,12,27,32]
>>> sum(num_list),'%i' % sum(num_list) '%.2f' % sum(num_list)

## 以指定的方式排序 list.sort(fn = None,key = None,reverse = False)
>>> num_list = [29,39,4,23,42,13,19,21]
>>> num_list.sort()     ## 改變list物件本身
>>> sorted(num_list)    ## 返回一個排序後的list物件,不改變num_list

## 按照key值排序
>>> key_list = [('name':3),('age':10),('num':23),('key':24)]
>>> key_list.sort(key = lambda x:x[1])

## 倒序排序
>>> key_list.sort(reverse = True)

## 正向排序
>>> key_list.sort(reverse = False)複製程式碼

Set型別

型別定義

  • 通過set定義普通集合
  • 通過frozenset定義不可變集合

簡單示例

## 初始化
set_list = [2,39,9,3,4,5,28,34]
>>> s1 = set(set_list)
{2, 3, 4, 5, 34, 39, 9, 28}

>>> s2 = frozenset(set_list)
frozenset({2, 3, 4, 5, 34, 39, 9, 28})

## 判斷包含關係
>>> print 9 in s1

## 判斷子集關係
>>> print s1 >= s2

## 差運算
>>> print s1 - s2

## 交運算
>>> print s1 & s2

## 執行並運算並賦值給s1
>>> print s1 |= s2

## 對稱差運算
>>> print s1 ^ s2 ## 獲取s1不在s2的元素以及s2不在s1的元素

## 集合遍歷
>>> for ele in s1:
...        print(ele)複製程式碼

Dictionary型別

型別定義

  • 即字典型別,代表一個鍵值儲存庫,類似於對映表

簡單示例

## 字典定義
>>> dc = {"name":"xiaokun","age":4,"title":"english name"}

## 讀取元素
>>> print dc['name']

## 直接通過下標增加字典欄位
>>> dc['new_name'] = 'new_value'

## 合併字典
>>> dc1 = {"name2":"xiaokun","age2":4,"title2":"english name"}
>>> dc.update(dc1)複製程式碼

相關文章