Python -- Lists
2016-01-14 23:52
399 查看
Python – Lists
注:初学者,基本翻译文档而来(version:3.5.1)Python中的Lists的书写形式如下所示:方括号之间使用逗号相隔。在Python中,Lists可以包含类型不同的条目(item,说元素或许更好熟悉),但是经常都是包含类型相同的条目。
>>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25]
和字符串一样,Lists也可以被索引(indexed)和切割(sliced)
>>> squares[0] #indexing returs the item 1 >>> squares[-1] 25 >>> squares[-3:] #slicing returns a new list [9, 16, 25]
切割操作返回的是一个全新的list, 即意味着下面的代码片段返回的list相当于是squares的拷贝。
>>> squares[:] [1, 4, 9, 16, 25]
Lists也支持串联(concatenation)操作
>>> squares + [-1, -4, -9, -16, -25] [1, 4, 9, 16, 25, -1, -4, -9, -16, -25]
和字符串是不可变(immutable)类型不一样的是,Lists是可变(mutable)的类型
例如下面的代码段,改变list中的内容。
>>> cubes = [1, 8, 27, 65, 125] #something is wrong here >>> 4 ** 3 #the cube of 4 is 64, not 65! 64 >>> cubes[3] = 64 #replace the wron 4000 g value >>> cubes [1, 8, 27, 64, 125]
可以使用append()方法在list的末尾添加条目
>>> cubes.append(216) #add the cube of 6 >>> cubes.append(7 ** 3) #add the cube of 7 >>> cubes [1, 8, 27, 64, 125, 216, 343]
通过切割操作,我们可以改变list的大小或者甚至完全清楚list中的items
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> letters ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> #replace some values ... >>> letters[2:5] = ['C', 'D', 'E'] >>> letters ['a', 'b', 'C', 'D', 'E', 'f', 'g'] >>> #now remove them ... >>> letters[2:5] = [] >>> letters ['a', 'b', 'f', 'g'] >>> #clear the list by replacing all the elements with an empty list ... >>> letters[:] = [] >>> letters []
库函数(built-in function)len()获取list的长度
>>> letters = [1, 2, 3, 4, 5] >>> len(letters) 5
list的条目也可以是list
>>> 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'
相关文章推荐
- python---三位数
- python安装splinter
- Python类属性访问的魔法方法
- Python---初识堡垒机
- windows7—32位环境安装theano
- Sublime Text 3 python 配置
- python序列
- Python基础学习
- 【学神-RHEL7】P6-Python字典的使用
- 从Theano到Lasagne:基于Python的深度学习的框架和库
- 用最大堆模拟最大优先级序列(Python实现)
- Python函数
- 公交车到站预测1----python处理csv文件
- 利用pandas进行数据分组及可视化
- python-列表与元组
- Python处理excel表格
- Python 2.7.x 和 3.x 版本的重要区别小结
- 欢迎使用CSDN-markdown编辑器
- python学习二(Django+eclipse完成增删改查)
- Python标准库07 信号 (signal包,部分os包)