Python3.7--数据结构--序列Sequence

序列的主要功能是资格测试(Membership Test)(也就是 in 与 not in 表达式)和索引 操作(Indexing Operations)
它们能够允许我们直接获取序列中的特定项目
之前学过的三个数据结构,列表、元组、字典与字符串,都可以使用序列来做。

今天学习几种操作方式

  • 数组[n] 第几个,从0开始
  • 数组[-n] 第几个,从最后一个开始,倒回来,也是从0开始
  • 数组[n:m] 从第N个到第M个
  • 数组[n:m:s] 从第n个开始到第m个结束,使用步长为s

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])
'''
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
'''
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
print("My name is ",name)
print('Character 0 is', name[0])

'''
Item -1 is banana
Item -2 is carrot
My name is  swaroop
Character 0 is s

'''
# Slicing on a list #.
print('Item all is ',shoplist)
print('Item 0 to 1 is', shoplist[0:1])
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[:])
'''
Item all is  ['apple', 'mango', 'carrot', 'banana']
Item 0 to 1 is ['apple']
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']
'''

# 从某一字符串中切片 #
print("My name is ",name)
print('characters 0 to 1 is', name[0:1])
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[:])
'''
My name is  swaroop
characters 0 to 1 is s
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
'''

从以上三个例子可以看出,序列是从0开始计算,然后到最后一个为止是不包括,比如0..1是不包括1的。
shoplist[3] 其实是第四位banana,shoplist[0]是第1个;
同样的内容,在字符串swaroop中也是一样的name[0],是s,name[2]是第三个字符为工a;
shoplist[1:-1],这里面有一个很奇怪的操作叫-1,就是返回字串不包括最一项,比如所以结果为['mango', 'carrot']
同样的characters 1 to -1 is waroo,这个表示是从第1(其实是第2个字符开始到不包括最后一位的串,所以是waroo,相当于去头去尾;

#还有一种操作使用步长[::1],就是为步长;
#把步长加1都打印出来
print(shoplist[::1])
#把步长加2都打印出来
print(shoplist[::2])
#从1开始把步长加2都打印出来
print(shoplist[1::2])
#把步长加3都打印出来
print('The step is 3',shoplist[::3])
print('The step is 4',shoplist[::4])

#把步长-2都打印出来
print('The step is -2',shoplist[::-2])

注意使用负号回来的值是倒序过来的。

你可能感兴趣的:(Python3.7--数据结构--序列Sequence)