序列的主要功能是資格測試(Membership Test)(也就是 in 與 not in 表達式)和索引 操作(Indexing Operations)
它們能夠允許我們直接獲取序列中的特定項目
之前學過的三個數(shù)據(jù)結構,列表、元組、字典與字符串,都可以使用序列來做。
今天學習幾種操作方式
- 數(shù)組[n] 第幾個,從0開始
- 數(shù)組[-n] 第幾個,從最后一個開始,倒回來,也是從0開始
- 數(shù)組[n:m] 從第N個到第M個
- 數(shù)組[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])
注意使用負號回來的值是倒序過來的。