侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python学习笔记基本数据结构之序列类型list tuple range用法分析

Python  /  管理员 发布于 7年前   228

本文实例讲述了Python学习笔记基本数据结构之序列类型list tuple range用法。分享给大家供大家参考,具体如下:

list 和 tuple

  • list:列表,由 [] 标识; 有序;可改变列表元素
  • tuple:元组,由 () 标识; 有序;不可改变元组元素(和list的主要区别)

list 和 tuple 的创建:

print([])   # 空listprint(["a",1,True])          # 元素类型不限print([x for x in range(0,6)])    # 列表推导式print(list("a"),type(list("a")))   # 强制转化print(())   # 空tupleprint((1))  # 不是tupleprint((1,))  # 单一元素tuple 一定要加,print(("a",1,True))          # 元素类型不限print(tuple("a"),type(tuple("a")))  # 强制转化

空list l = []

list 用一对方括号,用','隔开里面的元素  l = [a]   l = ["a",1,True]  元素类型不限

列表推导式,如:[x for x in range(0,6)] (下方会详细介绍 range 及 列表推导式)

类型转换 list()

空tuple  t = ()

tuple 若只有一个元素时,注意表示为  t = (1,)  一定要有逗号

tuple 用一对圆括号,用','隔开里面多个的元素  t = ("a",1,True)  元素类型不限

类型转换 tuple()

range

range 可方便的生成一个等差的序列,有两种表示 range(stop) 、range(start, stop[, step]) ; 通常用在 for循环语句中

range(stop) 表示 0 到 stop(不包含stop) 等差为1 的数,如 range(4) 表示 0 1 2 3

range(start, stop[, step]) 表示 从 start 到 stop(不包含stop) 等差为step的数;step缺省为1,可设置为负数

print(type(range(4)))          # range本身就是一个typefor i in range(4):  print(i)  # 0 1 2 3for i in range(-1):           # 从0计数,无值  print(i)for i in range(4,7):          # 4 5 6  print(i)for i in range(2,7,2):         # 2 4 6  print(i)for i in range(5,2,-1):         # 5 4 3  print(i)

序列操作

一般操作,不改变list本身

Operation Result
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n or n * s n shallow copies of s concatenated
s[i] ith item of s, origin 0
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
s.index(x[, i[, j]]) index of the first occurrence of x in s (at or after index i and before index j)
s.count(x) total number of occurrences of x in s

s = ["a",1,True,["b"],2]    print("a" in s)        # 判断元素存在于sprint("a" not in s)      # 判断元素不存在于sprint("b" in s)print(1.0 in s)        # 这边不判断int float类型不同print("1" in s)        # 这边的1为字符串a = [1,2]b = [2,1,0]print(a+b)           # 序列相加print(a*3)           # 序列乘法s = [0,1.0,2,3,4,5,6,7,8] print(s[0],s[2],s[3])     # 通过下标来取出对应的元素print(type(s[0]))      print(type(s[1]))print(s[2:4])         # 取出一段listprint(s[2:7:2])        # 根据步长取出一段listprint(len(s))         # list长度,即包含几个元素sum = 0for i in range(0,len(s)):   # 使用for循环来取出list的每个元素  print(s[i])  sum += i          # 赋值的简单表达式,相当于 sum = sum + iprint(sum)           # 总和print(min(s),max(s))      # 取最小/最大;注意元素类型间若不可比较,会报错s = [2,3,1,2,2,3]print(s.index(2))       # 查找对应元素第一次出现的下标# print(s.index(4))      # 不存在该元素会报错print(s.index(2,3))      # 从下标为3的开始找起print(s.index(2,3,4))     # 从下标为3到下标4的阶段内找print(s.count(2))       # 输出为2的元素的个数print(s.count("2"))      # 找不到匹配元素,返回0

上方列出的操作方法对 tuple 也都适用,因为并不改变序列本身的元素,如

s = (2,3,1,2,2,3)print(s[2],s[2:4],len(s),s.count(2))      # 对tuple均适用

改变序列的操作:仅对 list 适用;若对 tuple 操作,会报错;clear() 和 copy() 是 Python 3.3 才新增的方法

Operation Result
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j] same as s[i:j] = []
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.pop([i]) retrieves the item at i and also removes it from s
s.remove(x) remove the first item from s where s[i] == x
s.clear() removes all items from s (same as del s[:])
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.extend(t) extends s with the contents of t (same as s[len(s):len(s)] = t)
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
s.copy() creates a shallow copy of s (same as s[:])
s.reverse() reverses the items of s in place

list的增、删、改的操作实际都比较实用,需要熟练掌握

list元素更改

可对 list 不同的下标表示法做以下操作,一般 list 下标的操作仅作对单一元素的更改赋值,如 s[0]=1 ;对多个元素的操作见下方示例(仅供参考)

s = [0,1,2,3]s[0] = "1"print(s)# 对list的某一元素赋另外的值,类型也跟随改变s[4] = 1# 不可超过原list的长度,会报错s[0:3] = [2,3,4]        # 可对一段元素赋另外的值print(s)    s[0:3] = ["x","x"]        # 可缺少,元素个数也就相应的减少了print(s)    s[0:2] = ["x","x","x","x"]    # 可增加,元素个数也就相应的减加了print(s)  s[0] = [0,0]          # 单个元素注意,相当于赋值,把序列赋予该元素print(s)  s[1:2] = [0,0]        print(s)  s = [0,1,2,3,4,5,6,7,8]s[1:8:2] = ["x"]*4      # s[1:8:2] = ["x"]*3      # 这种表示方式元素个数一定需要相同,不然会报错print(s)

list元素删除

s = [0,1,2,3,4,5,6,7,8]del s[0:4]# 删除对应的元素  print(s)  s = [0,1,2,3,4,5,6,7,8]del s[1:8:2]           # 做删除print(s)s = [0,1,2,3,4,5,6,7,8]s.pop(3)print(s.pop(3),s)         # 做删除,并且返回该元素的值print(s.pop(),s)         # 默认删除最后一个s = [2,"1",1.0,1,2,1]s.remove(1)# 删除第一个值为 1 的元素print(s)          s.clear() # 置空,Python3.3引入print(s)

list元素增加

s = [0,1,2,3,4]s.append(5)# list 最后加一个元素print(s)s.extend([6,7])          # list 最后拼接序列print(s)s.extend(range(3))print(s)s.insert(1,["x"])         # 在1的位置插入["x"]print(s)

其他操作,reverse、copy 等

s = [1,2,3]c = s.copy()          # 相当于 c = sprint(c)c.reverse()print(c)s = [2,3,1,4]s.sort()# 排序print(s)# s = ["b",1,"a",True]     # 报错,必须是可比较的类型s = ["b","a"]s.sort()  print(s)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    Python基本数据结构之字典类型dict用法分析
    下一条:
    Python面向对象之类的封装操作示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客