1. 程式人生 > >python資料結構之序列及其操作

python資料結構之序列及其操作

序列

      在Python中最基本的資料結構是序列(sequence)。序列中的每個元素被分配一個序號----即元素的位置,也稱索引。索引從0開始,0,1,2,3,...。也可以從最後一個數開始,標記為-1,依次為-1,-2,-3....

列表與元組的區別:列表可以修改,元組不可修改。

通用序列操作

1.索引

索引示例:

#根據給定的年月日以數字形式打印出日期
months=[
    'January','February','March','April','May','June','July','August','Sepetember','October','November','December'
]
#以1~31的數字作為結尾的列表,給Day加字尾
ending=['st','nd','rd']+17*['th']+['st','nd','rd']+7*['th']+['st']
print(ending)
year=input('Year: ')
month=input('Month(1-12): ')
day=input('Day(1-31): ')

month_number=int(month)
day_number=int(day)

#記得要將月份和天數減一,以獲得正確的索引
month_name=months[month_number-1]
ordinal=day+ending[day_number-1]

print(month_name+' '+ordinal+'. '+year)


輸出:
#給日期後加字尾
['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st']
Year: 2018
Month(1-12): 1
Day(1-31): 1
January 1st. 2018

2.切片

使用切片操作來訪問一定範圍內的元素。切片通過冒號隔開兩個索引來實現:

a=[1,2,3,4,5,65,76,7,8,89,9,67,88]
print(a[7:10])#從表頭開始
print(a[7:-4])
print(a[-6:-4])#從表尾開始
#切片中最左邊的索引比右邊的晚出現在序列中,結果就是一個空序列
print(a[-6:0])
print(a[:])

輸出:
[7, 8, 89]
[7, 8]
[7, 8]
[]
[1, 2, 3, 4, 5, 65, 76, 7, 8, 89, 9, 67, 88]

步長:

步長是1,切片操作就按照這個 步長逐個遍歷序列的元素,然後返回開始和結束點之間的元素

程式碼實現:

a=[1,2,3,4,5,65,76,7,8,89,9,67,88]
print(a[0:13:2])

輸出:
[1, 3, 5, 76, 8, 9, 88]

None、空列表和初始化

None是一個Python的內建值,表示“這裡什麼都沒有”

#以正確的寬度在居中的“盒子”內列印一個句子
#獲取句子長度
sentence = input('Plese input a sentence:')
screen_width =100
#獲取文字的長度
text_width =len(sentence)
#文字的寬度
box_width = text_width +10
#計算出左右兩邊需空餘的格式數[左邊緣,右邊緣]
left_margin = (screen_width - box_width)//2
box_left_margin = (box_width-text_width)//2

#列印螢幕寬度
print('='*100)
print(' '*left_margin + '+' + '-' *(box_width-2) + '+')
print(' '*left_margin + '|' + ' ' *(box_width-2) + '|')
print(' '*left_margin + '|' + ' '*(box_left_margin-1) + sentence + ' '*(box_left_margin-1) + '|')
print(' '*left_margin + '|' + ' ' *(box_width-2) + '|')
print(' '*left_margin + '+' + '-' *(box_width-2) + '+')
#列印螢幕寬度
print('='*100)


輸出:
Plese input a sentence:Hello world
====================================================================================================
                                       +-------------------+
                                       |                   |
                                       |    Hello world    |
                                       |                   |
                                       +-------------------+
====================================================================================================