029-序列

list()

就是把一個(gè)對(duì)象拆分成一個(gè)列表。這個(gè)對(duì)象,要么是空的,就是一個(gè)空列表,要么必須是一個(gè)可迭代對(duì)象。

>>> a = list()
>>> a
[]
# 創(chuàng)建一個(gè)空列表
>>> b = list('YouAreSoHandsome')
>>> b
['Y', 'o', 'u', 'A', 'r', 'e', 'S', 'o', 'H', 'a', 'n', 'd', 's', 'o', 'm', 'e']
# 使用list(),將可迭代對(duì)象作為參數(shù),為變量賦值
>>> c = []
>>> for each in 'YouAreSoHandsome':
    c.append(each)

    
>>> c
['Y', 'o', 'u', 'A', 'r', 'e', 'S', 'o', 'H', 'a', 'n', 'd', 's', 'o', 'm', 'e']
>>> 
# 用for循環(huán),展示list()實(shí)現(xiàn)原理

tuple()

用法跟list()一樣,不同的地方在于把序列換成元組。

str()

將對(duì)象轉(zhuǎn)換為字符串。

len()

太熟悉了,略。

max() / min()

用于返回序列或者參數(shù)集合中的最大值、最小值。

實(shí)現(xiàn)原理如下:

>>> temp = [1,2,3,43,45,56,76,7,87,9]
>>> max = temp[0]
>>> for i in temp:
    if i > max:
        max = i

        
>>> max
87

sum(iterable[,start])

sum()方法用于返回序列中所有元素值的總和。其中start這個(gè)元素,指的是把它當(dāng)成整個(gè)加法過程中的第一個(gè)加數(shù)。例:

>>> tuple = 5,2,0,1,3,1,4
>>> sum(tuple,10000)
10016
>>> 

sorted()

類似于列表內(nèi)建方法中的“.sort()”,區(qū)別是,內(nèi)建方法只是把列表原地排序,而sorted()則是產(chǎn)生一個(gè)新的列表。

>>> list = [1,2,3,5,7,9,11,4,6]
>>> id(list)
1357468278208
>>> list.sort()
>>> list
[1, 2, 3, 4, 5, 6, 7, 9, 11]
>>> id(list)
1357468278208
>>> 
>>> list1 = list[:]
>>> id(list1)
1357428644736
>>> sorted(list1)
[1, 2, 3, 4, 5, 6, 7, 9, 11]
>>> id(sorted(list1))
1357468275072
>>> 

reversed()

用于返回逆向迭代序列的值。和內(nèi)建方法“.reverse()”的區(qū)別也是一個(gè)是原地翻轉(zhuǎn),一個(gè)是翻轉(zhuǎn)后返回。reversed()返回的是一個(gè)迭代器對(duì)象。

>>> list = [1,2,3,5,7,9,11,4,6]
>>> reversed(list)
<list_reverseiterator object at 0x0000013C0F6C3FD0>
>>> type(reversed(list))
<class 'list_reverseiterator'>
>>> for each in reversed(list):
    print(each,end=',')

    
6,4,11,9,7,5,3,2,1,
>>> 

enumerate()

enumerate的意思是列舉、枚舉的意思。他的作用是生成一個(gè)由二元組構(gòu)成的迭代對(duì)象。每一個(gè)二元組,由元素索引,和元素值構(gòu)成。例:

>>> enumerate('IloveU')
<enumerate object at 0x0000013C0F693B00>
>>> for each in enumerate('IloveU'):
    print(each,end='')
    print()

    
(0, 'I')
(1, 'l')
(2, 'o')
(3, 'v')
(4, 'e')
(5, 'U')

zip()

zip()方法將n個(gè)序列的內(nèi)容,共同組成一個(gè)由n元組構(gòu)成的可迭代對(duì)象。例:

>>> list = [1,2,3,4,5,6]
>>> tuple = ('A','B','C','D','E')
>>> str = '東西南北'
>>> zip(list,tuple,str)
<zip object at 0x0000013C0F68AF80>
>>> for each in zip(list,tuple,str):
    print(each,end=',')
    print()

    
(1, 'A', '東'),
(2, 'B', '西'),
(3, 'C', '南'),
(4, 'D', '北'),
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容