列表(list)

列表(list)


  1"""
  2和字符串一样, 列表支持索引访问.
  3列表是一个元素可重复, 可修改的序列.
  4列表的元素可以包括不同的类型, 甚至是None 但是, 一般也不要那么做.
  5
  6重点:列表推导式
  7"""
  8
  9
 10def list_intro():
 11    alist = [1, 1, 2, 3, 5, 8, 13, 21, 34]
 12    print(type(alist))
 13    print(alist[4])
 14    # Join 2 lists together
 15    blist = alist + [54, 89]
 16    print(blist)
 17    # List element can be changed
 18    blist[9] = 55
 19    print(blist)
 20    # Also, list support slice
 21    clist = ['apple', 'orange', 'grape', 'strawberry']
 22    print(clist[2:3])  # grape
 23    # Assigning a slice can also modify original list, even clear the list
 24    clist[2:3] = ['grape']
 25    print(clist)  # ['apple', 'orange', 'grape', 'strawberry']
 26    clist[3:] = []
 27    print(clist)  # ['apple', 'orange', 'grape']
 28    clist[:] = []
 29    print(clist)  # []
 30    # List has many useful APIs
 31    clist.append('banana')
 32    clist[len(clist):] = ['peach']
 33    print(clist)
 34    # List elements can be duplicated, and None
 35    dlist = ['country', 'province', 'state', 'country', 'street', None]
 36    print(dlist)
 37
 38
 39list_intro()
 40
 41
 42def list_shallow_copy():
 43    """
 44    列表的切片, 返回一个对列表的浅拷贝.
 45    以下操作, 返回了不同的结果.
 46    """
 47    rgba = ["Red", "Green", "Blue", "Alph"]
 48    # slice will return a shallow copy of a list
 49    rgba_correct = rgba[:]
 50    rgba[:] = ["Red", "Green", "Blue", "Alpha"]
 51    # rgba_correct[-1] = 'alpha'
 52    print(rgba)  # ['Red', 'Green', 'Blue', 'Alpha']
 53    print(rgba_correct)  # ['Red', 'Green', 'Blue', 'Alph']
 54
 55
 56list_shallow_copy()
 57
 58
 59class ListStack:
 60    """
 61    使用列表模拟栈
 62    """
 63
 64    # elements = [] 一般不在此处声明变量, 因为是public的(类变量)
 65
 66    # constructor
 67    def __init__(self, *args):
 68        # 此处的变量才是实例变量
 69        self.elements = list(args)
 70
 71    def push(self, ele):
 72        self.elements.append(ele)
 73
 74    def pull(self):
 75        if len(self.elements) > 0:
 76            return self.elements.pop()
 77        else:
 78            raise SystemError("stack is empty!")
 79
 80    def print_stack(self):
 81        print(self.elements)
 82
 83    def size(self):
 84        return len(self.elements)
 85
 86
 87stack = ListStack('wind', 'forest', 'fire')
 88stack.print_stack()
 89stack.push('mountain')
 90stack.print_stack()
 91print(stack.pull() + ', stack length is ' + str(stack.size()))
 92
 93
 94class ListQueue:
 95    """
 96    使用list实现队列
 97    更快的实现方式: from collections import deque
 98    """
 99
100    def __init__(self, *args):
101        self.elements = list(args)
102
103    def push(self, ele):
104        self.elements.append(ele)
105
106    def pull(self):
107        if self.size() > 0:
108            return self.elements.pop(0)
109        else:
110            raise SystemError("queue is empty!")
111
112    def size(self):
113        return len(self.elements)
114
115    def print_queue(self):
116        print(self.elements)
117
118
119queue = ListQueue(1, 3, 5)
120queue.print_queue()
121queue.push(7)
122print(queue.size())
123queue.pull()
124queue.print_queue()
125
126# ##################################### #
127# 列表推导式, 让创建列表的方式更加简单
128# 格式: 表达式 + for {[for...][if...]}
129# 解释: 一个表达式,后面为一个 for 子句,
130#      然后,是零个或多个 for 或 if 子句。
131#      结果是由表达式依据 for 和 if 子句
132#      求值计算而得出一个新列表。
133# ##################################### #
134
135# 以下初始化列表的方式
136squares = []
137for x in range(10):
138    squares.append(x ** 2)
139print(squares)
140# 等价于
141squares = list(map(lambda x: x ** 2, range(10)))
142# 还可以更加简单的表示成列表推导式
143squares = [x ** 2 for x in range(10)]
144
145# 还可以使用更加复杂的表达式
146sqlist = [(x, y) for x in (1, 2, 3) for y in (3, 1, 4) if x != y]
147print(sqlist)
148# 上面的表达式等价于
149sqlist = []
150for x in [4, 6, 9]:
151    for y in [5, 4, 6]:
152        if x != y:
153            sqlist.append((x, y))
154print(sqlist)
155
156# 利用表达式展开复杂的列表
157vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
158flat_vec = [e for l in vec for e in l]
159print(flat_vec)
160# 等价于
161vecc = []
162for i in vec:
163    for j in i:
164        vecc.append(j)
165print(vecc)
166
167# 前置表达式可以是更加复杂的表达式
168from math import pi
169
170pil = [str(round(pi, i)) for i in range(6)]
171print(pil)
172
173# 甚至, 是另一个列表推导式. 不过这种语句, 少用, 可读性太差
174matrix = [
175    [1, 2, 3, 4],
176    [5, 6, 7, 8],
177    [9, 10, 11, 12],
178]
179mat = [[i[k] for i in matrix] for k in range(4)]
180print(mat)
181# 等价于
182matt = []
183for i in range(4):
184    tmp = []
185    for j in range(len(matrix)):
186        tmp.append(matrix[j][i])
187    # for ele in matrix:
188    # tmp.append(ele[i])
189    matt.append(tmp)
190print(matt)
191
192# 可以使用内置函数zip替代
193print(list(zip(*matrix)))
194
195# del 语句 可以用来删除列表的元素, 或者整个变量
196del [matt[0]]
197print(matt)
198del matt
199print(matt)  # name 'matt' is not defined