小白教程

 找回密码
 立即注册

序列

发布者: 小白教程

列表,元组和字符串是序列的示例,但是什么是序列,它们的特殊之处是什么?

主要功能是成员资格测试(即innot in表达式)和索引操作,这些功能使我们可以直接获取序列中的特定项目。

上面提到的三种类型的序列-列表,元组和字符串,也具有切片操作,该操作使我们能够检索序列的切片,即序列的一部分。

示例(另存为ds_seq.py):

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

# Indexing or 'Subscription' operation #
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[:])

# Slicing on a string #
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都会为您提取与序列中该位置相对应的项目。请记住,Python从0开始计数。因此,shoplist[0]获取序列中的第一项并shoplist[3]获取第四项shoplist

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

通过指定序列的名称,然后在方括号内用冒号分隔可选的一对数字,来使用切片操作。请注意,这与您迄今为止一直在使用的索引操作非常相似。请记住,数字是可选的,但冒号不是可选的。

切片操作中的第一个数字(在冒号之前)指的是切片开始的位置,第二个数字(在冒号之后)表示切片将在的位置停止。如果未指定第一个数字,Python将在序列的开头开始。如果遗漏了第二个数字,Python将在序列末尾停止。请注意,返回的切片起始位置开始,并且将在结束位置之前终止,即包括开始位置,但从序列切片中排除了结束位置。

因此,shoplist[1:3]返回序列的一个切片,该切片从位置1开始,包括位置2,但在位置3处停止,因此返回两个项目切片同样,shoplist[:]返回整个序列的副本。

您也可以对负位置进行切片。负数用于从序列末尾开始的位置。例如,shoplist[:-1]将返回序列的切片,该切片不包含序列的最后一项,但包含其他所有内容。

您还可以为切片提供第三个参数,这是切片的步骤(默认情况下,步骤大小为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,...。当步长为3时,我们得到的位置是0、3等。

交互式地使用Python解释器尝试这种切片规范的各种组合,即提示,以便您可以立即看到结果。关于序列的妙处在于,您可以以相同的方式访问元组,列表和字符串!

上一篇:字典下一篇:集合

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 01:42 , Processed in 0.019363 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部