05-python_数据类型-元组

╰半橙微兮° 2022-09-17 06:28 298阅读 0赞

序列
-列表
-字符串
-元组

1. 序列的特点

1.1 索引 操作符

可从序列中抓取特定的项目.
从左往右数, firstIndex=0;从右往左数, firstIndex=-1
sequence[index] 如:

str=’0123456789’
str[0]
‘0’
str[-1]
‘9’

1.2 切片 操作符

获取序列的一个切片, 即获取子序列
sequence[start:end:step]如:

str=’0123456789’
str[1:5]
‘1234’

2. 序列的基本操作

2.1 基本操作
① len() 求序列长度
② + 连接两个序列
③ * 重复序列元素
④ in 判断元素是否在序列中
⑤ max() 返回最大值
⑥ min() 返回最小值
⑦ cmp(seq1,seq2) 比较两个序列值是否相同

2.2 举例 - 字符串为例

2.2.1 len()

str=’0123456789’
len(str)
10

2.2.2 +

str1 = ‘123’
str2 = ‘456’
str1 + str2
‘123456’

2.2.3 *

str = ‘xyZ’
str*3
‘xyZxyZxyZ’

2.2.4 in

str = ‘123’
‘1’ in str
True
‘-1’ in str
False

2.2.5 max() min()

str = ‘123’
max(str)
‘3’
str = ‘abc’
max(str)
‘c’

2.2.6 cmp(seq1,seq2) ,小于(-1),等于(0),大于(1)

str1=’12’
str2=’12’
cmp(str1, str2)
0
str1=’11’
str2=’22’
cmp(str1, str2)
-1
cmp(str2, str1)
1

3. 元组 - ()

3.1 概念
用小括号界定, 逗号分隔的一系列的值.
元组的值不可变, 即不能给指定的项目赋值.
如:

userinfo = (‘zhangsan’, 20, ‘man’)
userinfo
(‘zhangsan’, 20, ‘man’)
type(userinfo)

3.2 元组的创建
① 空 元组

empty = ()
type(empty)

② 单一元素 元组 (逗号结尾)
A. 错误

single = (1)
type(single)


B. 正确
single = (1,)
type(single)

③ 一般 元组

normal = (‘123’, 123)
type(normal)

3.3 元组的操作

3.3.1 说明
元组 也是 序列, 元组的值也不可变, 其操作类似于字符串.

3.3.2 基本操作

t = (0, 1, 2, 3)
t[0]
0
t[1:3]
(1, 2)

3.3.3 通过元组给变量赋值
(1) 不规范, 不推荐

a, b = 1, 2
a
1
b
2
(2) 推荐
a, b = (3, 4)
a
3
b
4
(3)
t = (5, 6)
a, b = t
a
5
b
6

发表评论

表情:
评论列表 (有 0 条评论,298人围观)

还没有评论,来说两句吧...

相关阅读