Python基礎(chǔ)之內(nèi)置類型與數(shù)據(jù)結(jié)構(gòu)

Data Structures

數(shù)值Numbers

簡單的數(shù)值計算,計算器功能
運(yùn)算符

+  -  *  /
//     #保留整數(shù)部分
%    #取余數(shù)
**     #power

字符串Strings

  1. 單引號和雙引號馍资,不沖突原則
  2. 單引號中\nprint時要換行,使用r前綴避免解釋轉(zhuǎn)意字符
  3. +,*操作
    3 * 'un' + 'ium' => unununium
    'Py' 'thon' => Python #這種操作只能簡單連接员凝,不能復(fù)合操作('un' * 3) 'ium'
  4. Strings can be indexed (subscripted)
word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
  1. 能索引就意味著能切片
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
  1. 看一看索引號,可以這樣認(rèn)為:正索引從0開始左閉右開响鹃,負(fù)索引從-1開始全閉
+---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
  1. 不可通過索引改變string的元素,Python strings cannot be changed — they are immutable
  2. len() returns the length of a string

列表Lists

  1. 通過[]定義列表squares = [1, 4, 9, 16, 25]
  2. 和String一樣List也是內(nèi)置的sequence類型所以能夠使用同樣的索引和切片方法
  3. Lists也支持合并+操作
  4. Lists是mutable的乎串,
  • 使用賦值=操作來改變元素值cubes[3] = 64或者letters[2:5] = ['C', 'D', 'E']
  • 在末尾加入新項cubes.append(216)
  1. 同樣可以使用len()返回長度
  2. 支持嵌套使用店枣,It is possible to nest lists (create lists containing other lists)。
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
  1. 下面總結(jié)一下Lists的操作方法
  • list.append(x)**:末尾增一項叹誉,這一項可以是各種對象鸯两。Add an item to the end of the list; equivalent to a[len(a):] = [x]

  • list.extend(L)**:先展開所增對象,然后在末尾一一增項长豁,Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L

  • list.insert(i, x)**:在i位置插入一項x钧唐。Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x)

  • list.remove(x)**:刪除值為x的索引值最小項。Remove the first item from the list whose value is x. It is an error if there is no such item.

  • list.pop([i])**:刪除并返回給定位置i的項蕉斜,如果使用pop()則是刪除最后一項并返回其值逾柿。Remove the item at the given position in the list, and return it. If no index is specified, a.pop()removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

  • list.index(x)**:返回值為x的第一項索引號。Return the index in the list of the first item whose value is x. It is an error if there is no such item.

  • list.count(x)**:返回x出現(xiàn)的次數(shù)宅此。Return the number of times x appears in the list.

  • list.sort(cmp=None, key=None, reverse=False)**: 排序机错。Sort the items of the list in place (the arguments can be used for sort customization.

  • list.reverse():倒轉(zhuǎn)Lists。Reverse the elements of the list, in place.

  1. 通過上面方法的總結(jié)父腕,通常以如下幾種方式使用List
  • Using Lists as Stacks (“l(fā)ast-in, first-out”):append and pop method,
  • Using Lists as Queues (“first-in, first-out”): using collections.deque
from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves'Eric'
>>> queue.popleft() # The second to arrive now leaves'John'
>>> queue # Remaining queue in order of arrivaldeque(['Michael', 'Terry', 'Graham'])

Functional Programming Tools: 函數(shù)式編程工具

有三個內(nèi)置函數(shù)在Lists的使用上非常方便:

  1. filer(function, sequence): 返回一個sequence弱匪,返回序列對原序列的篩選,篩選方法是function。返回的序列與原序列類型相同萧诫,可以使用這個方法篩選數(shù)據(jù)斥难。這里作為參數(shù)的function定義有一定要求,fucntion要有一個參數(shù)帘饶,并且其返回值只能是0或1,所以這個函數(shù)邏輯性的過濾函數(shù)
>>> def f(x): return x % 3 == 0 or x % 5 == 0
...
>>> filter(f, range(2, 25))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
  1. map(function,sequence,seq...): 返回一個sequence哑诊,返回序列各個項是function作用到原序列各個項獲得的結(jié)果。這里的作用函數(shù)特點(diǎn)是及刻,參數(shù)個數(shù)要與map的序列個數(shù)一致镀裤,并且各個序列的長度要一致。function返回與這些參數(shù)相關(guān)的值缴饭。這是一個典型的映射操作(map)暑劝。
  • 單序列映射
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
  • 多序列映射
def func2(x,y,z):  return x+y*z
a = range(7);  b = range(7,14)
dd = map(func2,a,b,a)
//result:[0, 9, 20, 33, 48, 65, 84]

map()的原理可以用下圖表示:


map(f, seq, seq, ...)
  1. reduce(function,seq) : reduce把一個函數(shù)作用在一個序列[x1, x2, x3...]上,這個函數(shù)必須接收兩個參數(shù)颗搂,reduce把結(jié)果繼續(xù)和序列的下一個元素做累積計算担猛,其效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)。注意丢氢,funciton的參數(shù)只能有兩個傅联。
    這里列舉幾個例子體會一下reduce()的使用:
  • 求和
>>> def add(x, y)
:...  return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
  • 把序列[1, 3, 5, 7, 9]變換成整數(shù)13579
def func3(x,y):
        return 10*x+y
ff = reduce(func3,[0,1,2,3,4])
print(ff)
#result: 1234
  • str轉(zhuǎn)換為int
def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def str2int(s): return reduce(lambda x,y: x*10+y, map(char2num, s))

List Comprehensions列表生成式

  1. range
 >>> range(1, 11)  
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1. for...in...
>>> L = []
>>> for x in range(1, 11):
...  L.append(x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  1. 列表生成式(一層循環(huán))
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

當(dāng)然,還可以用lambda&map來寫

map(lambda x: x*x, range(1,11))

但是卖丸,這樣表達(dá)沒有列表生成器簡明易讀(it’s more concise and readable)

  1. 列表生成式(兩層循環(huán)),所得列表長度等于循環(huán)次數(shù)
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
  1. 列表生成器(增加if判斷)
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Tuples and Sequences 元組和序列

A tuple consists of a number of values separated by commas. tuple通常用()表示纺且,tuple屬于immutable類型的序列,不支持賦值操作稍浆,但是它可以嵌套mutable的list類型( however it is possible to create tuples which contain mutable objects, such as lists.).

  • tuple packing: t = 12345, 54321, 'hello!'
  • tuple unpacking: x,y,z = t
  • tuple元素為異構(gòu)的载碌,通過unpack或index方式訪問;sequence元素為同構(gòu)的衅枫,通過iterator方式訪問
  • 兩種特殊的tuple
# tuple with zero or one element
>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> singleton
('hello',)
  • tuple packing and unpacking
t = 12345, 54321, 'hello!'             # packing
x, y, z = t                            # unpacking
  • 遍歷list, 按索引值和value值顯示, enumerate
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
  • 同時遍歷兩個list, zip
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))

Sets 集合

A set is an unordered collection with no duplicate elements.Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.Note: to create an empty set you have to use set(), not{},創(chuàng)建空set要使用set()不能用{}

  • list生成set
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
  • string生存set
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
  • 集合操作
    • a - b : 差集 in a but not in b
    • a | b : 或集 in either a or b
    • a & b : 并集 in both a and b
    • a ^ b : (a | b) - (a & b) in a or b but not both
  • set comprehensions集合生成器
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
set(['r', 'd'])
  • 添加與刪除方法
    • add(key)
    • remove(key)

Dictionaries字典

  • 刪除一個元素, del(dic)
  • 列出所有的key, list(dic)
  • 按value排序key, sorted(dic)
  • 判斷key是否存在, key in dic
  • 遍歷字典
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末嫁艇,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子弦撩,更是在濱河造成了極大的恐慌步咪,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件益楼,死亡現(xiàn)場離奇詭異猾漫,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)感凤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門悯周,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人陪竿,你說我怎么就攤上這事禽翼。” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵闰挡,是天一觀的道長锐墙。 經(jīng)常有香客問我,道長长酗,這世上最難降的妖魔是什么溪北? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮花枫,結(jié)果婚禮上刻盐,老公的妹妹穿的比我還像新娘。我一直安慰自己劳翰,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布馒疹。 她就那樣靜靜地躺著佳簸,像睡著了一般。 火紅的嫁衣襯著肌膚如雪颖变。 梳的紋絲不亂的頭發(fā)上生均,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天,我揣著相機(jī)與錄音腥刹,去河邊找鬼马胧。 笑死,一個胖子當(dāng)著我的面吹牛衔峰,可吹牛的內(nèi)容都是我干的佩脊。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼垫卤,長吁一口氣:“原來是場噩夢啊……” “哼威彰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起穴肘,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤歇盼,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后评抚,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體豹缀,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年慨代,在試婚紗的時候發(fā)現(xiàn)自己被綠了邢笙。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡鱼响,死狀恐怖鸣剪,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤筐骇,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布债鸡,位于F島的核電站,受9級特大地震影響铛纬,放射性物質(zhì)發(fā)生泄漏厌均。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一告唆、第九天 我趴在偏房一處隱蔽的房頂上張望棺弊。 院中可真熱鬧,春花似錦擒悬、人聲如沸模她。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽侈净。三九已至,卻和暖如春僧凤,著一層夾襖步出監(jiān)牢的瞬間畜侦,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工躯保, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留旋膳,地道東北人。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓途事,卻偏偏與公主長得像验懊,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子盯孙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容