天天看點

《Python進階程式設計》學習心得——第五章 序列《Python進階程式設計》學習心得——第五章 序列

《Python進階程式設計》學習心得——第五章 序列

總覽

Python内置的序列類有list, tuple, deque, str, array等,分類如下:

《Python進階程式設計》學習心得——第五章 序列《Python進階程式設計》學習心得——第五章 序列

+、+=和extend()方法的差別

+=實際上是調用了__iadd__方法實作的,而__iadd__又調用了extend方法,是以+=和extend一樣,可以将兩個序列對象相加。而+隻能将兩個同類的對象相加(如list + list, tuple + tuple).

a = [1,2]
b = [3,4]
c = (3,4)
a + b
>>> [1,2,3,4]
a + c
>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list
a += c
>>> [1,2,3,4]
a.extend(c)
>>> [1,2,3,4,3,4]
           

自定義可切片對象

class Group:
    def __init__(self, company, staffs):
        self.company = company
        self.staffs = staffs

    def __len__(self):
        return len(self.staffs)

    def __iter__(self):
        return iter(self.staffs)

    def __getitem__(self, item):
        cls = type(self)
        return cls(self.company, self.staffs[item])

    def __contains__(self, element):
        return element in self.staffs

    def __str__(self):
        return 'Company: ' + self.company + ' Staff: ' + str(self.staffs)


if __name__ == '__main__':
    group = Group('HIT', ('Euy', 'Obuy', 'Ouhz', 'Naij'))
    print(group[0])             # __getitem__
    print(group[:2])            # __getitem__
    print(len(group))           # __len__
    print('Euy' in group)       # __contains__
    for staff in group:         # __iter__
        print(staff)
           

執行結果

Company: HIT Staff: Euy
Company: HIT Staff: ('Euy', 'Obuy')
4
Euy
Obuy
Ouhz
Naij
True
           

bisect維護有序序列

>>> a = [3,4,5,61,1,1,2]
>>> a.sort()
>>> a
[1, 1, 2, 3, 4, 5, 61]
>>> bisect.insort(a, 8)
>>> a
[1, 1, 2, 3, 4, 5, 8, 61]
>>> bisect.bisect_left(a, 4)
4
>>> bisect.bisect_right(a, 4)
5
>>> bisect.bisect(a, 4)
5
           

bisect子產品的方法主要有

insort			# 插入有序表
bisect			# 二分查找傳回index
bisect_left		
bisect_right
           

等,都是與二分查找有關,對于長度為N的對象,複雜度都是O(logN).

array.array

array與list功能類似,差別在于array中的元素必須事先指定類型,而且array中的元素必須是同一個類型的,而list不需要滿足上面兩個條件。

相比于list,array性能更高。如果要序列中的元素類型事先已知,可以考慮用array.

>>> import array
>>> arr = array.array('i')	# only support integer
>>> arr.append(1)
>>> arr.append(2)
>>> arr
array('i', [1, 2])
>>> a = [1,2,'a']			# support different types of elements
           

清單推導式、生成器表達式、字典推導式

清單推導式

>>> a = [x+1 for x in range(10) if x < 5]
>>> a
[1, 2, 3, 4, 5]
           

生成器表達式

>>> a = (x+1 for x in range(10) if x < 5)
>>> a
<generator object <genexpr> at 0x0000014BDB1CB8E0>
>>> b = list(a)
>>> b
[1, 2, 3, 4, 5]
           

字典推導式

>>> my_dict = {'a':1, 'b':2, 'c':3}
>>> reverse_dict = {value:key for key, value in my_dict.items()}
>>> reverse_dict
{1: 'a', 2: 'b', 3: 'c'}
>>> my_set = {key for key, value in my_dict.items()}
>>> my_set
{'a', 'b', 'c'}