python列表介绍list
list 是python最常用的复合数据类型,格式:
写在方括号之间、用逗号分隔开的数值列表。
列表内的项目不必全是相同的类型。
>>> a = ['sp', 'eg', 10, 34] >>> a ['sp', 'eg', 10, 34]
可以被索引和切片。python也是从0开始是计数的。
切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。数是可选的,而冒号是必须的。
切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。如果不指定第一个数,Python就从序列首开始。如果没有指定第二个数,则Python会停止在序列尾。注意,返回的序列从开始位置 开始 ,刚好在 结束 位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。
$ python Python 3.5.2 (default, Sep 14 2017, 22:51:06) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a = ['sp', 'eg', 10, 34] >>> a ['sp', 'eg', 10, 34] >>> a[0] 'sp' >>> a[-1] 34 >>> a[:2] ['sp', 'eg'] >>>
列表的拼接操作
>>> a + [1,24] ['sp', 'eg', 10, 34, 1, 24] >>>
修改list中的元素
>>> a[1] = 99 >>> a ['sp', 99, 10, 34] >>>
可以通过使用append()方法在列表的末尾添加新项
>>> a.append(1234) >>> a ['sp', 99, 10, 34, 1234] >>>
修改指定区间的列表值
$ python Python 3.5.2 (default, Sep 14 2017, 22:51:06) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> let = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> let ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> #替换 ... let[2:5] = ['x', 'y', 'z'] >>> let ['a', 'b', 'x', 'y', 'z', 'f', 'g'] >>> #删除 ... let[2:5] = [] >>> let ['a', 'b', 'f', 'g'] >>> #清空 ... let[:] = [] >>> let [] >>>
嵌套列表
>>> a = ['a', 'b', 'c'] >>> n = [1, 2, 3] >>> x = [a, n] >>> x [['a', 'b', 'c'], [1, 2, 3]] >>> x[0] ['a', 'b', 'c'] >>> x[0][1] 'b'
移除列表中的元素:3种方法
1)n.pop(index):会返回移除的元素
Python 3.5.2 (default, Sep 14 2017, 22:51:06) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> n = ['a', 'b', 'c'] >>> n.pop(1) 'b' >>> print (n) ['a', 'c'] >>>
2)n.remove(item):移除实际的元素
>>> n.append('d') >>> print (n) ['a', 'c', 'd'] >>> n.remove('d') >>> print (n) ['a', 'c'] >>>
3) del(n[index]) :和.pop效果一样,但是不会有返回值
>>> del(n[1]) >>> print(n) ['a'] >>>
- 多个列表的迭代zip:取对应两个中的最大值
$ python
Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> list_a = [1, 2, 3, 4, 5]
>>> list_b = [0, 5, 1, 3, 6, 7]
>>> for a, b in zip(list_a, list_b):
... print (max(a,b)),
...
1
5
3
4
6