python 切片獲取list、tuple中的元素

記憶殘留發表於2017-07-17
#-*- coding:UTF-8 -*-
L=[]
n=6
r=[1,2,3,4,5,6]
for  i  in range(n):
    L.append(r[i])

print   L  # =>[1, 2, 3, 4, 5, 6]
#取所有
print  L[:]   # => [1, 2, 3, 4, 5, 6]
#取前三個
print L[0],L[1],L[2] # => 1 2 3
print  L[0:3]   # => [1, 2, 3]

#取第三個和第四個
print L[2:4] #= >[3, 4]

#取倒數第一個
print  L[-1:] # =>[6]

print  L[-4:-2]

#取前四個
print  L[:4]  # =>[1, 2, 3, 4]

#建立一個0-99的數列:
L=range(100)
#取前十個
print  L[:10]    # =>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#後十個
print  L[-10:]   # =>  [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

#前10個,每兩個取一個
print  L[:10:2]     # => [0, 2, 4, 6, 8]

#所有數,每5個取一個
print L[::5]

# ==>[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]


#tuple也是一種list,唯一區別是tuple不可變,tuple也可以用切片操作,操作結果仍是tuple

print (0,1,2,3,4,5)[:3]   #  ==> (0, 1, 2)

#字串'xxx'或Unicode字串u'XXX'也可以看成一種list,每個元素就是一個字元,操作結果仍是字串:
print  'abcdefg'[:3]    #  ==>>abc

print  'ABCDEFGHI'[::2]   #  ==>> ACEGI

 

相關文章