《Python高级编程》学习心得——第五章 序列

《Python高级编程》学习心得——第五章 序列

总览

Python内置的序列类有list, tuple, deque, str, array等,分类如下:
《Python高级编程》学习心得——第五章 序列_第1张图片

+、+=和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 "", 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'}

你可能感兴趣的:(Python)