类型和运算(三):列表

类型:列表

python列表与字符串一样作为序列的一种。但与字符串不同的是,它没有固定的大小。列表支持索引和分片的操作。

>>> L = [123,'apple',1.23]
>>> L
[123, 'apple', 1.23]
>>> L[0]
123
>>> L[1:]
['apple', 1.23]
>>> L[:-2]
[123]
>>> L + [4,5,6]
[123, 'apple', 1.23, 4, 5, 6]
>>> L
[123, 'apple', 1.23]
>>> 

类型的特定操作

1.列表的append方法可以扩充列表的大小并在尾部插入一项;

>>> L
[123, 'apple', 1.23]
>>> L.append('orange')
>>> L
[123, 'apple', 1.23, 'orange']
>>> 

2.列表的pop方法移除给定偏移量的一项。

>>> L
[123, 'apple', 1.23, 'orange']
>>> L.pop(2)
1.23
>>> L
[123, 'apple', 'orange']
>>> 

3.列表的sort方法默认对列表进行升序排列。reverse则对列表进行翻转。

>>> A = ['zz','aa','yy','cc']
>>> A
['zz', 'aa', 'yy', 'cc']
>>> A.sort()
>>> A
['aa', 'cc', 'yy', 'zz']
>>> A.reverse()
>>> A
['zz', 'yy', 'cc', 'aa']
>>> 

边界检查

尽管列表是可变大小的,但是仍然不允许引用不存在的元素。超出列表末尾之外的索引会导致错误,对列表末尾赋值同样会导致错误。

>>> L
[123, 'apple', 'orange']
>>> L[99]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> L[99] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> 

列表的嵌套

python的核心数据类型的一个优秀特性是支持任意的嵌套,你可以在列表中嵌套一个字典然后在字典中嵌套一个列表。

>>> M = [[1,2,3],[4,5,6],[7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> M[0]
[1, 2, 3]
>>> M[0][0]
1
>>> 

列表的解析

>>> col = [row[1] for row in M]
>>> col
[2, 5, 8]

本文为菜鸟学习笔记,如有错误,请各位大神帮忙指出,感激不尽。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容