Python3 More on Lists.md

列表对象方法

len(L)
计算列表的长度。注意:列表第一个元素的下标是从 0 开始的,因此,最后一个元素的下标是 len(list) - 1


append(x)
添加 1 个元素到列表的末尾。相当于 list[len(list): ] = [x]

>>> list = [0, 1, 2];
>>> list.append(3);
>>> list 
[0, 1, 2, 3]

extend(L)
将列表 L 中所有的元素添加到列表的末尾。相当于 list[len(list): ] = L

>>> list = [0, 1, 2];
>>> L = [3, 4, 5];
>>> list.extend(L);
>>> list
[0, 1, 2, 3, 4, 5]    # 注意,是将列表 L 的所有元素添加到列表的末尾,不是添加列表 L 本身

insert(i, x)
在列表给定的位置插入 1 个元素。i 索引号,x 要插入的值。
如果 list[i] 已经存在,若 0 <= i < len(list),则在 list[i] 位置插入值 x ,原 list[i] 及其后面的数据向后移。若 -len(list) =< i <= -1,则在 list[i - 1] 位置插入值,原 list[i] 及其后面的值向后移.
如果 i < -len(list),则都是在 list[0] 插入值。
如果 i >= len(list),则都是在 list[len(list)] 插入值。

>>> list = [0, 1, 2];
>>> list.insert(0, -1);    # 在已有的 list[i],且 '0 <= i < len(list)' 中插入值
>>> list
[-1, 0, 1, 2]
>>> list.insert(-3, 'i');    # 在已有的 list[i],且 '-len(list) =< i <= -1' 中插入值
>>> list
[-1, 'i', 0, 1, 2]
>>> list.insert(-100, -2);    # 在 'i < -len(list)',插入值
>>> list
[-2, -1, 'i', 0, 1, 2]
>>> list.insert(100, 3);    # 在 'i >= len(list)',插入值
>>> list
[-2, -1, 'i', 0, 1, 2, 3]

remove(x)
删除列表中第 1 个值为 x 的元素。如果没有值为 x 的元素就会报错。

>>> list = [0, 1, 2, 3, 1];
>>> list.remove(1);
>>> list
[0, 2, 3, 1]
>>> list.remove('a');
Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    list.remove('a');
ValueError: list.remove(x): x not in list

pop([i])i 两边的 square brackets 表示 i 是可以选参数,而不是要你输入 []。)
删除列表中下标为 i 的值,并且返回该值。如果未指定索引,则会删除并返回列表最后一个值。如果 i 不存在,即超出了列表的范围,就会报错。

>>> list = [0, 1, 2, 3, 4, 5];
>>> list.pop(1);    # 正索引删除值
1        # 会自动返回删除的值
>>> list
[0, 2, 3, 4, 5]
>>> list.pop(-2);    # 负索引删除值
4
>>> list
[0, 2, 3, 5]
>>> list.pop(100);    # 删除不在列表已存在值的范围内索引值,会报错
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    list.pop(100);
IndexError: pop index out of range
>>> list.pop(-100);
Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    list.pop(-100);
IndexError: pop index out of range

clear()
删除列表中所有的值。相当于 del list[ : ];

>>> list = [0, 1, 2, 3];
>>> list.clear();
>>> list
[]
>>> list = [0, 1, 2, 3];
>>> del list[ : ];
>>> list
[]
>>> list = [0, 1, 2, 3];
>>> del list;
>>> list
<class 'list'>

index(x)
返回列表中第 1 个值为 x 的元素的索引。如果没有这样的元素就会报错。

>>> list = [0, 2, 2, 5];
>>> list.index(2);
1
>>> list.index(1);
Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    list.index(1);
ValueError: 1 is not in list

count(x)
返回列表中 x 出现的次数。如果列表中没有该值就会返回 0。

>>> list = [0, 1, 1, 3];
>>> list.count(1);
2
>>> list.count(2);
0

sort()
Sort the items of the list in place (the arguments can be used for sort cusmization, see sorted() for their explanation).
原地排序列表中的元素。

>>> list = [2, 1, 3, 5, 0, 4];
>>> list.sort();
>>> list
[0, 1, 2, 3, 4, 5]

list.sort() 之后列表 list 是在本身 sort。但如果想要一个排序好的副本,同时保持原有的列表不变,要怎么实现?

# 方法一:先产生一个副本,再排序。
>>> list = [2, 1, 3, 5, 0, 4];
>>> copy = list[ : ]; 
>>> copy.sort();
>>> list
[2, 1, 3, 5, 0, 4]
>>> copy
[0, 1, 2, 3, 4, 5];

# 方法二:用 sorted() 排序,sorted() 函数会返回一个列表的副本。
>>> list = [2, 1, 3, 5, 0, 4];
>>> copy = sorted(list);
>>> list
[2, 1, 3, 5, 0, 4]
>>> copy
[0, 1, 2, 3, 4, 5];

注意:创建副本的时候不能够直接赋值 copy = list,这只是 copy 引用了 list


reverse()
Reverse the elements of the list in place.
原地反转列表的元素。

>>> list = [0, 1, 2, 3]
>>> list.reverse()
>>> list
[3, 2, 1, 0]

copy()
Return a shallow copy of the list. Equivalent to list[ : ].
返回列表的一个浅拷贝。等同于 list[ : ]

>>> list = [0, 1, 2, 3]
>>> copy = list.copy()
>>> copy
[0, 1, 2, 3]




Using Lists as Stacks

列表对象方法 append() pop() 使得将列表当作堆栈(后进先出)非常容易。
append() 添加元素到栈顶;pop() 删除栈顶的元素。

>>> stack = [0, 1, 2, 3]
>>> stack.append(4)
>>> stack
[0, 1, 2, 3, 4]
>>> stack.pop()
>>> stack
[0, 1, 2, 3]




Using List as Queues

也可以将列表当作队列(先进先出)使用。但列表用作队列效率不高。在列表的末尾添加和删除元素非常快,但是在列表的开头插入或删除元素却很慢(因为,所有的其它元素都要向后移一位)。
如果想要实现一个队列,可以使用 collections.deque,它设计的目的就是在两端都能够快速添加和弹出元素。

>>> from collections import deque
>>> dir(deque)
['__add__', '__bool__', '__class__', '__contains__', '__copy__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'appendleft', 'clear', 'copy', 'count', 'extend', 'extendleft', 'index', 'insert', 'maxlen', 'pop', 'popleft', 'remove', 'reverse', 'rotate']
>>> queue = deque([0, 1, 2, 3])
>>> queue.append(4)
>>> queue
deque([0, 1, 2, 3, 4])
>>> queue.pop()
4
>>> queue
deque([0, 1, 2, 3])
>>> queue.popleft()
0
>>> queue
deque([1, 2, 3])
>>> queue.appendleft(0)
>>> queue
deque([0, 1, 2, 3])




List Comprehensions 列表解析

列表解析提供了一个生成列表的简洁方法。应用程序通常会从一个序列的每个元素的操作结果生成新的列表,或者生成满足特定条件的子序列。
例如,我们要创建一个列表 squares:

>>> squares = []
>>> for x in range(10) :
        squares.append(x**2)

>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> x
9

注意,这个 for 循环中被创建的名为 x 的变量在循环完毕后依然存在。

我们可以用列表解析来实现 squares 列表,并且不会产生存留 x 变量等副作用。

>>> squares = [v**2 for v in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> v    # 变量 v 是不存在的
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    v
NameError: name 'v' is not defined

列表解析,由 [] 括起来,括号里面包含一个表达式,表达式后面跟着一个 for 语句,后面还可以接零个或者多个 forif 语句。结果是一个新的列表,由表达式依据其后的 for if 子句产生的结果构成。
利用列表解析组合两个列表中不相等的元素:

>>> combs = [(x, y) for x in [0, 1, 2] for y in [1, 2, 3] if x != y]
>>> combs
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 1), (2, 3)]

它等效于:

>>> combs = []
>>> for x in [0, 1, 2] :
    for y in [1, 2, 3] :
        if x != y :
            combs.append((x, y))
    
>>> combs
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 1), (2, 3)]
>>> list = [-3, -2, -1, 0, 1, 2, 3]
>>> abs = [abs(x) for x in list]
>>> abs
[3, 2, 1, 0, 1, 2, 3]

>>> list = ['a', 'B', 'C', 'd']
>>> upper = [x.upper() for x in list]
>>> upper
['A', 'B', 'C', 'D']
>>> uppers = [(x.lower(), x.upper()*3) for x in list]
>>> uppers
[('a', 'AAA'), ('b', 'BBB'), ('c', 'CCC'), ('d', 'DDD')]
>>> [x.upper(), x.upper()*2 for x in list]
SyntaxError: invalid syntax

>>> list = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> list1 = [x for y in list for x in y]    # flatten a list
>>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Nested List Comprehensions 嵌套的列表解析

m x n 的矩阵列表 matrix 转换成 n x m 的矩阵列表

>>> matrix = [[0, 1, 2, 3], [4, 5, 6,7], [8, 9, 10, 11]]
>>> transpose = [[x[i] for x in matrix] for i in range(len(matrix[0]))]
>>> transpose
[[0, 4, 8], [1, 5, 9], [2, 6, 10], [3, 7, 11]]

思路:从 matrix 的每个元素(也是列表)中取出索引一样的元素,组成一个新的列表:[x[i] for x in matrix]。同时,我们要限定索引 i 的范围:for i in range(len(matrix[0]))。注意,不能够这样 for i in range(len(x)),因为,x 是在内层定义的的。

>>> transpose = [[x[i] for x in matrix] for i in range(len(x))]
NameError: name 'o' is not defined

上面的代码等效于:

>>> matrix = [[0, 1, 2, 3], [4, 5, 6,7], [8, 9, 10, 11]]
>>> transpose = []
>>> for i in range(len(matrix[0])) :
            transpose.append([x[i] for x in matrix])

>>> transpose
[[0, 4, 8], [1, 5, 9], [2, 6, 10], [3, 7, 11]]

更详细地:

>>> matrix = [[0, 1, 2, 3], [4, 5, 6,7], [8, 9, 10, 11]]
>>> transpose = []
>>> for i in range(len(matrix[0])) :
        row = []
        for x in matrix :
                row.append(x[i])
        transpose.append(row)

>>> transpose
[[0, 4, 8], [1, 5, 9], [2, 6, 10], [3, 7, 11]]

要实现上面的矩阵转换,使用 Python 的 built-in function 实现更加简单:

>>> list(zip(*matrix))    # Python3 zip() 返回一个对象,所以,要转换成列表
[[0, 4, 8], [1, 5, 9], [2, 6, 10], [3, 7, 11]]
>>> # 函数调用时使用 * 操作符将参数从列表或元组中分拆开来,否则:
>>> list(zip(matrix))
[([0, 1, 2, 3],), ([4, 5, 6, 7],), ([8, 9, 10, 11],)]

zip(*iterables)

Make an iterator that aggregates elements from each of the iterables. Returns an iterator(Python3, it's type is object) of tuples.

Python2,zip() 返回结果是列表类型;Python3,zip() 返回结果是一个对象。所以,我们要对返回值进行转换。

>>> type(zip())
<class 'zip'>

>>> x = [0, 1, 2]
>>> y = ['a', 'b', 'c']
>>> zip = zip(x, y)
>>> zip
<zip object at 0x00000000014DEEC8>
>>> list(zip)
[(0, 'a'), (1, 'b'), (2, 'c')]    # Returns an iterator of tuples.

>>> type(zip())
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    type(zip())
TypeError: 'list' object is not callable
'这里为什么会出现这样的错误呢??? 因为,用 zip 作为变量了(Python 定义变量的同时要赋值),当我们调用某个 function 的时候,如果前面定义了相同名字的变量,就会出现这样的错误。所以,定义变量的时候尽量不要和内建函数名字相同'

# 使用 zip 合并相邻的列表项
>>> a = [0, 1, 2, 3, 4, 5]
>>> list(zip(*([iter(a)] * 2)))
[(0, 1), (2, 3), (4, 5)]


The del statement del 语句

del 语句 可以按索引来删除列表中的一个 item。这不同于有返回值的 pop() 方法。del 语句还可以删除列表中的切片或整个列表(这些我们之前都是通过将一个空列表 [] 赋值个切片或整个列表来实现)。

>>> a = [0, 1, 2, 3, 4, 5]
>>> del a[0]
>>> a
[1, 2, 3, 4, 5]
>>> del a[1: 3]
>>> a
[1, 4, 5]
>>> del a[ : ]    # 删除列表 a 的所有元素 `a[ : ]`
>>> a
[]    # 空列表,列表 a 仍然存在的
>>> del a    # 删除列表 a,列表不存在了
>>> a
NameError: name 'a' is not defined



转载于:https://www.cnblogs.com/lizsCnBlog/p/4960250.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值