点击返回Python数据分析从入门到精通系列主页
创建列表
Python用[]创建列表,列表中元素可以是不同数据类型
>>> list = ['hello','python','30','逍遥']
>>> print(list)
['hello', 'python', '30', '逍遥']
>>>
添加元素
>>> list.append('test')
>>> print(list)
['hello world', 'python', '30', '逍遥', 'test']
>>>
删除元素
>>> del list[2]
>>> print(list)
['hello world', 'python', '逍遥', 'test']
>>>
获取指定元素
>>> list[1]
'python'
>>>
改变列表
>>> list[0] = 'hello world'
>>> print(list)
['hello world', 'python', '30', '逍遥']
>>>
列表遍历
>>> for n in list:
... print(n)
...
hello world
python
逍遥
test
>>>
列表截取
>>> print(list)
['hello world', 'python', '逍遥', 'test']
>>> list[1:] #输出从第二个元素开始后所有的元素
['python', '逍遥', 'test']
>>> list[1:3] #输出第二、三个元素 左闭右开
['python', '逍遥']
>>> list[-2] #输出从又往左第二个元素
'逍遥'
Python列表函数&方法
Python包含以下函数:
序号 | 函数 |
---|---|
1 | len(list) 列表元素个数 |
2 | max(list) 返回列表元素最大值 |
3 | min(list) 返回列表元素最小值 |
4 | list(seq) 将元组转换为列表 |
Python包含以下方法:
序号 | 方法 |
---|---|
1 | list.append(obj) 在列表末尾添加新的对象 |
2 | list.count(obj) 统计某个元素在列表中出现的次数 |
3 | list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
4 | list.index(obj) 从列表中找出某个值第一个匹配项的索引位置 |
5 | list.insert(index, obj) 将对象插入列表 |
6 | list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
7 | list.remove(obj) 移除列表中某个值的第一个匹配项 |
8 | list.reverse() 反向列表中元素 |
9 | list.sort( key=None, reverse=False) 对原列表进行排序 |
10 | list.clear() 清空列表 |
11 | list.copy() 复制列表 |