Python中的基本list操作[通俗易懂]
Python,基本,list,操作,通俗易懂
2025-04-07 09:01:25 时间
大家好,又见面了,我是你们的朋友全栈君。
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操作ES数据库「建议收藏」
- 人生苦短,python更短
- Python脚本
- [Python从零到壹] 十六.文本挖掘之词云热点与LDA主题分布分析万字详解
- python encode和decode函数说明[通俗易懂]
- shell中调用python函数,发送邮件
- javascript typescript_typescript python
- RPC协议及其python实例[通俗易懂]
- Python-drf前戏38.1-前端Vue01
- CPD 算法实现点云配准(python版本)[通俗易懂]
- python 字符串去空格
- python读写json_python格式化json
- Python实现智能停车场车牌识别计费系统
- Python基础16-正则和子进程模块
- python报错invalid syntax_fatal python error
- 【python】Excel转json「建议收藏」
- 如何设置python的环境变量_anaconda环境变量手动设置
- 简单的Python端口扫描工具制作
- python break和continue
- 支持向量机(SVM)的分析及python实现「建议收藏」