python编程组合数据类型_Python组合数据类型概述

前段时间我们(假想)学习了Python的基本数据类型:整数、浮点数和复数以及基本操作,无须回顾,现在我们来学习组合数据类型。组合数据类型能将多个同类型或不同类型的数据组织起来序列类型

序列类型是一个元素向量,元素之间存在先后关系,可以通过序列序号访问,元素可以重复。集合类型

集合类型是一个元素集合,元素之间无序,不可通过序号访问,元素在集合唯一存在。映射类型

映射类型是“键-值”数据项的组合,每一个元素是一个键值对,通过键的形式访问,表示为(key:value)。

常用4类序列数据类型的操作符或函数在与不在:in、not in

符合返回True,否则返回False。

>>> str='Hold the door!'#字符串

>>> x='d'

>>> x in str

True

>>> x not in str

False

>>> list=['cat','dog',1,2,3]#列表

>>> y='dog'

>>> y in list

True

>>> y not in list

False

>>> tuple=('cat','dog',1,2,3)#元组

>>> y in tuple

True

>>> y not in tuple

False只有加乘,再无减除:+、*

#复制n次

>>> str*3

'Hold the door!Hold the door!Hold the door!'

>>> list*3

['cat', 'dog', 1, 2, 3, 'cat', 'dog', 1, 2, 3, 'cat', 'dog', 1, 2, 3]

>>> tuple*3

('cat', 'dog', 1, 2, 3, 'cat', 'dog', 1, 2, 3, 'cat', 'dog', 1, 2, 3)

#直接连接

>>> str*3+str

'Hold the door!Hold the door!Hold the door!Hold the door!'

>>> list*3+list

['cat', 'dog', 1, 2, 3, 'cat', 'dog', 1, 2, 3, 'cat', 'dog', 1, 2, 3, 'cat', 'dog', 1, 2, 3]

>>> tuple*3+tuple

('cat', 'dog', 1, 2, 3, 'cat', 'dog', 1, 2, 3, 'cat', 'dog', 1, 2, 3, 'cat', 'dog', 1, 2, 3)序号访问与区间访问:索引s[i],分片s[i:j],步骤分片s[i:j:k]。

>>> str='Hold the door!'*3

>>> str[3]*3

'ddd'

>>> str[3:-1]#左闭右开

'd the door!Hold the door!Hold the door'

>>> str[3:]#自第三个字符起选择全部

'd the door!Hold the door!Hold the door!'

>>> str[:]#全部

'Hold the door!Hold the door!Hold the door!'

>>> str[::2]#步长为2

'Hl h orHl h orHl h or'

>>> str[::-1]#逆序返回

'!rood eht dloH!rood eht dloH!rood eht dloH'长度len,最大最小max/min,元素位置s.index,子串出现次数s.count。

s.index(x[,i[,j]]):序列s中[i,j+1]中第一次出现x的位置。

s.count(x):序列s中出现x的次数。

>>> tuple=('cat','dog',1,2,3)

>>> len(tuple)

5

>>> max(tuple)

Traceback (most recent call last):

File "", line 1, in

max(tuple)

TypeError: '>' not supported between instances of 'int' and 'str'

#注意,比较大小的时候,元素类型要一致

>>> max(str)

't'

>>> min(str)

' '

>>> tuple.index('dog')

1

>>> str.count('d')

6>>> print("{:-^20s}".format("编写结束"))

--------编写结束--------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值