1. 程式人生 > >《零基礎入門學習》Python(16)--序列!序列!

《零基礎入門學習》Python(16)--序列!序列!

前言

  • 你可能發現了,元組,字串放在一起講是有道理的,它們有許多共同點。(當然前面沒有看也能看這章)
  • 都可以通過索引得到每一個元素
  • 預設索引值總是從0開始
  • 可以通過分片的方法得到一個範圍內的元素的集合
  • 有很多共同的操作符(* 重複操作符、+ 拼接操作符、in not in成員關係操作符)

我們把這三種類型統稱為序列。

知識點

介紹下序列常見的BIF()

  • list(iterable) 把一個可迭代物件轉換為列表

  • iterable——迭代物件——所謂迭代,就是重複反饋過程的活動,其目的通常是為了接近並達到所需的目標或結果,每一次對過程的重複,被稱之為一次迭代

    。而每一次迭代的結果,都會變成下一次迭代的初始值。 
    所以呢,目前來說,迭代就是一個for迴圈。我們今後會介紹迭代器,那時迭代就不會僅僅是一個for了。

    >>> b = 'i love fishc.com'
    >>> b = list(b)
    >>> b
    ['i', ' ', 'l', 'o', 'v', 'e', ' ', 'f', 'i', 's', 'h', 'c', '.', 'c', 'o', 'm']
    #b本來是一個字串,然後通過list方法,把字串迭代,變成一個列表,然後賦值給回b。
    
    >>> c = (1,1,2,3,5,8,13,21,34)
    >>> c = list(c)
    >>> c
    [1, 1, 2, 3, 5, 8, 13, 21, 34]
    #c從元組變成了列表
    

     

  • tuple([iterable]) 把一個可迭代物件轉換為元組
  • >>> a = ['123',['a','b'],4,5,'c']
    >>> tuple(a)
    ('123', ['a', 'b'], 4, 5, 'c')

     

  • str(object) 把object物件轉換為字串
    ​>>> a = ['123',['a','b'],4,5,'c']
    >>> type(a)
    <class 'list'>
    
    >>> a = str(a)
    >>> a
    "['123', ['a', 'b'], 4, 5, 'c']"
    >>> type(a)
    <class 'str'>
    
    ​
  •  len(sub) 返回sub的長度
    >>> a
    ['123', ['a', 'b'], 4, 5, 'c']
    >>> len(a)
    5
    
    >>> a = str(a)
    >>> a
    "['123', ['a', 'b'], 4, 5, 'c']"
    >>> len(a)
    30
  •  max()返回序列或者引數集合中的最大值
    >>> numbers = [1,18,13,0,-98,34,54,76,32]
    >>> max(numbers)
    76
  •  min()返回序列或者引數集合中的最小值
    >>> numbers = [1,18,13,0,-98,34,54,76,32]
    >>> min(numbers)
    -98
    
    >>> chars = '1234567890'
    >>> min(chars)
    '0'
    
    >>> tupe1 = (1,2,3,4,5,6,7,8,9,0)
    >>> max(tupe1)
    9
    >>> min(tupe1)
    0
    
    #【注意】:使用max,min方法都要保證序列或者引數的資料型別都是一致的,否則會報錯:
    >>> mix = ['a','c',1,32,'d']
    >>> max(mix)
    Traceback (most recent call last):
      File "<pyshell#32>", line 1, in <module>
        max(mix)
    TypeError: '>' not supported between instances of 'int' and 'str'
    
  • sum(iterable[,start=0]) 返回序列iterable和可選引數start的總和
    >>> tuple2 = (3.1,2.3,3.4)
    >>> sum(tuple2)
    8.8
    >>> numbers
    [1, 18, 13, 0, -98, 34, 54, 76, 32]
    >>> numbers.append('a')
    
    >>> sum(numbers)
    Traceback (most recent call last):
      File "<pyshell#70>", line 1, in <module>
        sum(numbers)
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    
    >>> numbers.pop()
    'a'
    
    >>> numbers
    [1, 18, 13, 0, -98, 34, 54, 76, 32]
    >>> sum(numbers)
    130
    >>> sum(numbers,8)
    138
    >>> 
    
  • sorted(iterable, key=None, reverse=False) 返回一個排序的列表,使用方法跟列表的內建函式(list.sort())一致,注意,這個sorted()後邊有“ed”哦。

    >>> numbers
    [1, 18, 13, 0, -98, 34, 54, 76, 32]
    >>> sorted(numbers)
    [-98, 0, 1, 13, 18, 32, 34, 54, 76]

     

  • reversed(sequence)返回逆向迭代序列的值,一樣道理,跟列表的內建函式(list.reverse())一致,注意,這個reversed()後邊也多了個“d”哦。

    >>> numbers
    [1, 18, 13, 0, -98, 34, 54, 76, 32]
    
    >>> reversed(numbers)
    <list_reverseiterator object at 0x000000BE2F19E780>
    
    >>> list(reversed(numbers))
    [32, 76, 54, 34, -98, 0, 13, 18, 1]
    

     

  • enumerate(iterable) 生成由每個元素的index值和item值組成的元組

    >>> numbers
    [1, 18, 13, 0, -98, 34, 54, 76, 32]
    >>> enumerate(numbers)
    <enumerate object at 0x000000BE2F43DEE8>
    >>> list(enumerate(numbers))
    [(0, 1), (1, 18), (2, 13), (3, 0), (4, -98), (5, 34), (6, 54), (7, 76), (8, 32)]
    

     

zip(iter1 [,iter2 […]]) 返回由各個引數的序列組成的元組

>>> a = [1,2,3,4,5,6,7,8]
>>> b = [4,5,6,7,8]
>>> zip(a,b)
<zip object at 0x000000BE2F4193C8>
>>> list(zip(a,b))
[(1, 4), (2, 5), (3, 6), (4, 7), (5, 8)]

課後習題

測試題

  • 我們根據列表、元組和字串的共同特點,把它們統稱什麼?
序列
  • 請問分別使用什麼BIF,可以把一個可迭代物件轉換為列表、元組和字串?
list([iterable])  轉換為列表
tuple([iterable]) 轉換為元組
str(obj)   轉換為字串
  • 你還能複述出“迭代”的概念嗎?
所謂迭代,就是重複反饋過程的活動,其目的通常是為了接近並達到所需的目標或結果,
每一次對過程的重複,被稱之為一次`迭代`。而每一次迭代的結果,都會變成下一次迭代的初始值。
  • 你認為呼叫max('I love FishC.com')會返回什麼值?為什麼?
>>> max('I love FishC.com')
'v'

因為字串在計算機中是以ASCII碼的形式儲存,引數中ASCII碼值最大的是’v’ 對應118.

動動手

  • **猜想一下min()這個BIF的實現過程
def min(x):
    least = x[0]

    for each in x:
        if each < least:
            least = each

    return least

print(min('123456789'))
​​​​​​​
  • 視訊中我們說sun()這個BIF有個缺陷,就是如果引數裡有字串型別的話,就會報錯,請寫出一個新的實現過程,自動”無視”引數裡的字串並返回正確的計算結果
def sum(x):
    result = 0

    for each in x:
        if (type(each) == int ) or (type(each) == float):
            result += each
        else:
            continue

    return result

print(sum([1,2.1,2.3,'a','1',True]))