国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

python中l(wèi)ist列表的高級(jí)函數(shù)

2019-11-25 16:47:15
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

在Python所有的數(shù)據(jù)結(jié)構(gòu)中,list具有重要地位,并且非常的方便,這篇文章主要是講解list列表的高級(jí)應(yīng)用,基礎(chǔ)知識(shí)可以查看博客。
此文章為python英文文檔的翻譯版本,你也可以查看英文版:https://docs.python.org/2/tutorial/datastructures.html

use a list as a stack: #像棧一樣使用列表

stack = [3, 4, 5] stack.append(6) stack.append(7) stack [3, 4, 5, 6, 7] stack.pop() #刪除最后一個(gè)對(duì)象 7 stack [3, 4, 5, 6] stack.pop() 6 stack.pop() 5 stack [3, 4]

use a list as a queue: #像隊(duì)列一樣使用列表

> from collections import deque #這里需要使用模塊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'])

three built-in functions: 三個(gè)重要的內(nèi)建函數(shù)

filter(), map(), and reduce().
1)、filter(function, sequence)::
按照f(shuō)unction函數(shù)的規(guī)則在列表sequence中篩選數(shù)據(jù)

> def f(x): return x % 3 == 0 or x % 5 == 0... #f函數(shù)為定義整數(shù)對(duì)象x,x性質(zhì)為是3或5的倍數(shù)> filter(f, range(2, 25)) #篩選[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

2)、map(function, sequence):
map函數(shù)實(shí)現(xiàn)按照f(shuō)unction函數(shù)的規(guī)則對(duì)列表sequence做同樣的處理,
這里sequence不局限于列表,元組同樣也可。

> def cube(x): return x*x*x #這里是立方計(jì)算 還可以使用 x**3的方法...> map(cube, range(1, 11)) #對(duì)列表的每個(gè)對(duì)象進(jìn)行立方計(jì)算[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

注意:這里的參數(shù)列表不是固定不變的,主要看自定義函數(shù)的參數(shù)個(gè)數(shù),map函數(shù)可以變形為:def func(x,y) map(func,sequence1,sequence2) 舉例:

 seq = range(8)  #定義一個(gè)列表> def add(x, y): return x+y #自定義函數(shù),有兩個(gè)形參...> map(add, seq, seq) #使用map函數(shù),后兩個(gè)參數(shù)為函數(shù)add對(duì)應(yīng)的操作數(shù),如果列表長(zhǎng)度不一致會(huì)出現(xiàn)錯(cuò)誤[0, 2, 4, 6, 8, 10, 12, 14]

3)、reduce(function, sequence):
reduce函數(shù)功能是將sequence中數(shù)據(jù),按照f(shuō)unction函數(shù)操作,如 將列表第一個(gè)數(shù)與第二個(gè)數(shù)進(jìn)行function操作,得到的結(jié)果和列表中下一個(gè)數(shù)據(jù)進(jìn)行function操作,一直循環(huán)下去…
舉例:

def add(x,y): return x+y...reduce(add, range(1, 11))55

List comprehensions:
這里將介紹列表的幾個(gè)應(yīng)用:
squares = [x**2 for x in range(10)]
#生成一個(gè)列表,列表是由列表range(10)生成的列表經(jīng)過(guò)平方計(jì)算后的結(jié)果。
[(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)] 這里是生成了一個(gè)列表,列表的每一項(xiàng)為元組,每個(gè)元組是由x和y組成,x是由列表[1,2,3]提供,y來(lái)源于[3,1,4],并且滿足法則x!=y。

Nested List Comprehensions:
這里比較難翻譯,就舉例說(shuō)明一下吧:

matrix = [          #此處定義一個(gè)矩陣...   [1, 2, 3, 4],...   [5, 6, 7, 8],...   [9, 10, 11, 12],... ][[row[i] for row in matrix] for i in range(4)]#[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

這里兩層嵌套比較麻煩,簡(jiǎn)單講解一下:對(duì)矩陣matrix,for row in matrix來(lái)取出矩陣的每一行,row[i]為取出每行列表中的第i個(gè)(下標(biāo)),生成一個(gè)列表,然后i又是來(lái)源于for i in range(4) 這樣就生成了一個(gè)列表的列表。

The del statement:
刪除列表指定數(shù)據(jù),舉例:

> a = [-1, 1, 66.25, 333, 333, 1234.5]>del a[0] #刪除下標(biāo)為0的元素>a[1, 66.25, 333, 333, 1234.5]>del a[2:4] #從列表中刪除下標(biāo)為2,3的元素>a[1, 66.25, 1234.5]>del a[:] #全部刪除 效果同 del a>a[]

Sets: 集合

> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> fruit = set(basket)        # create a set without duplicates>>> fruitset(['orange', 'pear', 'apple', 'banana'])>>> 'orange' in fruit         # fast membership testingTrue>>> 'crabgrass' in fruitFalse>>> # Demonstrate set operations on unique letters from two words...>>> a = set('abracadabra')>>> b = set('alacazam')>>> a                 # unique letters in aset(['a', 'r', 'b', 'c', 'd'])>>> a - b               # letters in a but not in bset(['r', 'd', 'b'])>>> a | b               # letters in either a or bset(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])>>> a & b               # letters in both a and bset(['a', 'c'])>>> a ^ b               # letters in a or b but not bothset(['r', 'd', 'b', 'm', 'z', 'l'])

Dictionaries:字典

>>> tel = {'jack': 4098, 'sape': 4139}>>> tel['guido'] = 4127 #相當(dāng)于向字典中添加數(shù)據(jù)>>> tel{'sape': 4139, 'guido': 4127, 'jack': 4098}>>> tel['jack'] #取數(shù)據(jù)4098>>> del tel['sape'] #刪除數(shù)據(jù)>>> tel['irv'] = 4127   #修改數(shù)據(jù)>>> tel{'guido': 4127, 'irv': 4127, 'jack': 4098}>>> tel.keys()    #取字典的所有key值['guido', 'irv', 'jack']>>> 'guido' in tel #判斷元素的key是否在字典中True>>> tel.get('irv') #取數(shù)據(jù)4127

也可以使用規(guī)則生成字典:

>>> {x: x**2 for x in (2, 4, 6)}{2: 4, 4: 16, 6: 36}

enumerate():遍歷元素及下標(biāo)
enumerate 函數(shù)用于遍歷序列中的元素以及它們的下標(biāo):

>>> for i, v in enumerate(['tic', 'tac', 'toe']):...   print i, v...0 tic1 tac2 toe

zip():
zip()是Python的一個(gè)內(nèi)建函數(shù),它接受一系列可迭代的對(duì)象作為參數(shù),將對(duì)象中對(duì)應(yīng)的元素打包成一個(gè)個(gè)tuple(元組),然后返回由這些tuples組成的list(列表)。若傳入?yún)?shù)的長(zhǎng)度不等,則返回list的長(zhǎng)度和參數(shù)中長(zhǎng)度最短的對(duì)象相同。利用*號(hào)操作符,可以將list unzip(解壓)。

>>> 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)...What is your name? It is lancelot.What is your quest? It is the holy grail.What is your favorite color? It is blue.

有關(guān)zip舉一個(gè)簡(jiǎn)單點(diǎn)兒的例子:

>>> a = [1,2,3]>>> b = [4,5,6]>>> c = [4,5,6,7,8]>>> zipped = zip(a,b)[(1, 4), (2, 5), (3, 6)]>>> zip(a,c)[(1, 4), (2, 5), (3, 6)]>>> zip(*zipped)[(1, 2, 3), (4, 5, 6)]

reversed():反轉(zhuǎn)

>>> for i in reversed(xrange(1,10,2)):...   print i...

sorted(): 排序

> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']> for f in sorted(set(basket)):       #這里使用了set函數(shù)...   print f...applebananaorangepear

python的set和其他語(yǔ)言類似, 是一個(gè) 基本功能包括關(guān)系測(cè)試和消除重復(fù)元素.

To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

>>> words = ['cat', 'window', 'defenestrate']>>> for w in words[:]: # Loop over a slice copy of the entire list....   if len(w) > 6:...     words.insert(0, w)...>>> words['defenestrate', 'cat', 'window', 'defenestrate']

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宜阳县| 曲水县| 湘西| 尤溪县| 彭泽县| 朝阳市| 榆林市| 浮梁县| 濉溪县| 梁河县| 金华市| 库尔勒市| 平昌县| 黎平县| 衡东县| 青铜峡市| 伊吾县| 于都县| 义马市| 柘荣县| 虹口区| 马公市| 临邑县| 邮箱| 九龙城区| 道孚县| 嘉荫县| 祁东县| 祥云县| 翼城县| 洛隆县| 台北县| 富顺县| 吉首市| 连云港市| 临夏市| 淄博市| 青冈县| 信阳市| 巴青县| 色达县|