Python中的基本list操作[通俗易懂]
2023-06-13 09:12:11 时间
大家好,又见面了,我是你们的朋友全栈君。
List是python中的基本数据结构之一,和Java中的ArrayList有些类似,支持动态的元素的增加。list还支持不同类型的元素在一个列表中,List is an Object。
最基本的创建一个列表的方法
myList = [‘a’,’b’,’c’]
在python中list也是对象,所以他也有方法和属性,在ptython解释器中 使用help(list)可以查看其文档,部分开放方法如下:
在接下来的代码中,将使用这些方法:
1 # coding=utf-8
2
3 # Filename : list.py
5 # Date: 2012 11 20
6
7
8
9 # 创建一个list方式
10 heatList = ['wade','james','bosh','haslem']
11 tableList = list('123') #list方法接受一个iterable的参数
12
13 print 'Miami heat has ',len(heatList),' NBA Stars , they are:'
14
15 #遍历list中的元素
16 for player in heatList:
17 print player,
18
19
20 #向list添加元素
21 heatList.append('allen') #方式一:向list结尾添加 参数object
22 print '\nAfter allen join the team ,they are: '
23 print heatList
24
25 heatList.insert(4,'lewis') #方式二:插入一个元素 参数一:index位置 参数二:object
26 print 'After lewis join the team, they are:'
27 print heatList
28
29 heatList.extend(tableList) #方式三:扩展列表,参数:iterable参数
30 print 'After extend a table list,now they are :'
31 print heatList
32
33 #从list删除元素
34 heatList.remove('1') #删除方式一:参数object 如有重复元素,只会删除最靠前的
35 print" Remove '1' ..now '1' is gone\n",heatList
36
37 heatList.pop() #删除方式二:pop 可选参数index删除指定位置的元素 默认为最后一个元素
38 print "Pop the last element '3'\n",heatList
39
40 del heatList[6] #删除方式三:可以删除制定元素或者列表切片
41 print "del '3' at the index 6\n",heatList
42
43
44 #逻辑判断
45
46 #统计方法 count 参数:具体元素的值
47 print 'james apears ',heatList.count('wade'),' times'
48
49 #in 和 not in
50 print 'wade in list ? ',('wade' in heatList)
51 print 'wade not in list ? ',('wade' not in heatList)
52
53 #定位 index方法:参数:具体元素的值 可选参数:切片范围
54 print 'allen in the list ? ',heatList.index('allen')
55 #下一行代码会报错,因为allen不在前三名里
56 #print 'allen in the fisrt 3 player ? ',heatList.index('allen',0,3)
57
58 #排序和反转代码
59 print 'When the list is reversed : '
60 heatList.reverse()
61 print heatList
62
63 print 'When the list is sorted: '
64 heatList.sort() #sort有三个默认参数 cmp=None,key=None,reverse=False 因此可以制定排序参数以后再讲
65 print heatList
66
67 #list 的分片[start:end] 分片中不包含end位置的元素
68 print 'elements from 2nd to 3rd ' , heatList[1:3]
以上都是list最基本的操作,当然还包括和其他数据结构之间的转操作,注:python sort用的是稳定的排序算法
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/155996.html原文链接:https://javaforall.cn
相关文章
- python中矩阵的转置怎么写_Python 矩阵转置的几种方法小结
- python编程是什么-Python编程
- python实现各大视频网站电影下载
- python常见运维脚本_Python运维常用脚本[通俗易懂]
- python抛出异常和捕获异常_Python异常
- python读取excel并写入excel_python如何读取文件夹下的所有文件
- python deepcopy函数_Python deepcopy
- 正则表达式Python_python正则表达式匹配字符串
- Python使用platform库获取系统信息:操作系统信息、硬件信息、python环境信息
- Python的字符串,list,tuple,set,字典操作详解程序员
- python判断指定的端口是否被占用详解编程语言
- 学习Python精通SQL Server操作技巧(python操作sqlserver)
- Linux升级:升级Python到最新版本(linux升级python版本)
- Python与MongoDB 无缝连接(python连接mongodb)
- Python驱动Oracle数据库(python操作oracle)
- 使用 attrs 来告别 Python 中的样板
- Redis中的List数据结构详解(redis中list数据)
- Linux 下 Python 升级:轻松完成升级操作(linux下升级python)
- Python中使用MySQL数据库的操作技巧(mysql_python)
- 如何快速将List写入Redis(向redis写入list)
- python实现apahce网站日志分析示例
- Python实现的简单万年历例子分享