列表:列表是一种数据项构成的有限序列,即按照一定的线性顺序,排列而成的数据项的集合,在这种数据结构上进行的基本操作包括对元素的的查找,插入,和删除。
1.python列表:
python中的列表可以看成是一个高层集合,列表中的元素类型可以不统一,甚至列表中的元素仍然可以是一个列表。
代码:>>>stu_info=['14001','张三','男',19,495.5]
>>> print(stu_info)
['14001', '张三', '男', 19, 495.5]
>>> movies=['The Life','Dog Faces', ['Viliam', 'Marry',['The Brain of Doing', 'Great Man']]]
>>> print(movies)['The Life','Dog's Face', ['Viliam', 'Marry',['The Brain of Doing', 'Great Man']]]
python列表中的元素的索引值从0开始,通过索引值可以访问或处理列表中的任一元素。
代码:
>>> movies=['The Life','Dog Faces', ['Viliam', 'Marry',['The Brain of Doing', 'Great Man']]]
>>> print(movies[1])
Dog Faces
>>> print(movies[2][2][1])
Great Man
>>> movies=['The Life','Dog Faces', ['Viliam', 'Marry',['The Brain of Doing', 'Great Man']]]
>>> print(movies[-1]) ##当索引值为负数,指索引从末尾开始索引,-1表示倒数第一个元素,以此类推
['Viliam', 'Marry', ['The Brain of Doing', 'Great Man']]
>>> print(movies[2:]) ##截取列表中的元素,表示从第三个元素开始处理
[['Viliam', 'Marry', ['The Brain of Doing', 'Great Man']]]
2.列表处理:元素删除、插入、操作符运算
删除列表元素:
代码:
>>> movies.pop(1) ##list.pop(index)删除并返回列表元素,index为列表中元素索引,若不设置,则删除最后一项
'Dog Faces'
>>> print(movies)
['The Life', ['Viliam', 'Marry', ['The Brain of Doing','Great Man']]]
>>> movies.remove('The Life') ##list.remove(obj)删除列表中元素,obj为列表中元素值
>>> print(movies)
[['Viliam', 'Marry', ['The Brain of Doing', 'GreatMan']]]
插入列表元素:
代码:
>>> movies.insert(0,'The Life') ##list.insert(index,obj)为列表插入元素,index为对象需要插入的索引位置,obj为插入元素值
>>> print(movies)
['The Life', ['Viliam', 'Marry', ['The Brain of Doing', 'Great Man']]]
>>> movies.insert(1,'Dog Faces')
>>> print(movies)
['The Life', 'Dog Faces', ['Viliam', 'Marry', ['The Brain of Doing', 'Great Man']]]
>>> movies.append('Sunshine') ##list.append(obj)为列表末尾插入元素
>>> print(movies)
['The Life', 'Dog Faces', ['Viliam', 'Marry', ['The Brain of Doing', 'Great Man']], 'Sunshine']
>>> s1=[1,2,3,4]
>>> s2=[5,6,7,8]
>>> s1.extend(s2) ##list.extend(list2)在列表末尾增加另一个列表的所有元素
>>> print(s1)
[1, 2, 3, 4, 5, 6, 7, 8]
列表脚本操作符:
列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。
python表达式 | 结果 | 描述 |
[1,3,5]+[2,4,6] | [1,3,5,2,4,6] | 组合 |
['hi']*4 | ['hi','hi','hi','hi'] | 重复 |
3 in [1,2,3] | Ture | 元素是否存在与列表 |
for i in [1,3,5]:print i | 1 3 5 | 迭代 |
其他处理:
代码:
>>> s='hello world'
>>> print(len(s)) ##len(obj)函数返回对象(字符串、列表、元组)的长度或项目个数
11
>>>s2=['1','2','3','4'] ##反转列表中的元素
>>> s2.reverse()
>>> print(s2)
['4', '3', '2', '1']
>>> print(sorted(s2)) ##sorted(list)对列表进行排序
['1', '2', '3', '4']
>>> print(max(s2)) ##max(list)返回列表中最大值
4
>>> print(min(s2)) ##min(list)返回列表中最小值
1
>>> s2=['1','2','3','1','5']
>>> s2.count('1') ##list.count(obj)统计列表中元素为obj出现的次数
2
>>> s2.index('5') ##list.index(obj)读取列表中元素的索引值
4