序列_Sequence

列表、元组和字符串可以看作序列(Sequence) 的某种表现形式

序列的主要功能是资格测试(Membership Test) (也就是 innot in 表达式) 和索引操作(Indexing Operations) ,它们能够允许我们直接获取序列中的特定项目。

上面所提到的序列的三种形态——列表、元组与字符串,同样拥有一种切片(Slicing) 运算符,它能够允许我们序列中的某段切片——也就是序列之中的一部分。

案例(保存为 ds_seq.py ) :

# 序列(Sequence)

shoplist = ['apple','mango','carrot','banana']
name = 'swaroop'

# Indexing or 'Subscription' operation #
# 索引或“下标(Subscription) ”操作符 #
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
print('Character 0 is', name[0])

# Slicing on a list #
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])

# 从某一字符串中切片 #
print('characters 1 to 3 is', name[1:3])
print('characters 2 to end is', name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])

输出

$ python ds_seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Character 0 is s
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop

它是如何工作的

Python 从 0 开始计数。因此 shoplist[0]将获得 shoplist 序列中的第一个项目,而 shoplist[3]将获得第四个项目。

索引操作也可以使用负数,在这种情况下,位置计数将从队列的末尾开始。因此, shoplist[-1] 指的是序列的最后一个项目, shoplist[-2]将获取序列中倒数第二个项目。

在切片操作中,第一个数字(冒号前面的那位) 指的是切片开始的位置,第二个数字(冒号后面的那位) 指的是切片结束的位置。如果第一位数字没有指定,Python 将会从序列的起始处开始操作。如果第二个数字留空,Python 将会在序列的末尾结束操作。要注意的是切片操作会在开始处返回 start,并在 end 前面的位置结束工作。也就是说,序列切片将包括起始位置,但不包括结束位置

因此, shoplist[1:3]返回的序列的一组切片将从位置 1 开始,包含位置 2 并在位置 3 时结束,因此,这块切片返回的是两个项目。类似地, shoplist[:]返回的是整个序列。

你同样可以在切片操作中使用负数位置。使用负数时位置将从序列末端开始计算。例如,shoplist[:-1]强返回一组序列切片,其中不包括序列的最后一项项目,但其它所有项目都包含其中。

步长

你同样可以在切片操作中提供第三个参数,这一参数将被视为切片的步长(Step) (在默认情况下,步长大小为 1) :

>>> shoplist = ['apple', 'mango', 'carrot', 'banana']
>>> shoplist[::1]
['apple', 'mango', 'carrot', 'banana']
>>> shoplist[::2]
['apple', 'carrot']
>>> shoplist[::3]
['apple', 'banana']
>>> shoplist[::-1]
['banana', 'carrot', 'mango', 'apple']

你会注意到当步长为 2 时,我们得到的是第 0、2、4…… 位项目。当步长为 3 时,我们得到的是第 0、3……位项目。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值