?Python主要數(shù)據(jù)類型包括list(列表)毫炉、tuple(元組)、dict(字典)和set(集合)等對象华弓,下面逐一介紹這些Python數(shù)據(jù)類型奕筐。
? ? list(列表)是Python內置的一種數(shù)據(jù)類型,作為一個有序的數(shù)據(jù)集合,list的元素是可變的,可隨意添加或刪減list中的元素。在Python交互式命令中運行l(wèi)ist相關代碼:
>>> list_1 = ['one', 'two','three']
>>> list_1
['one', 'two', 'three']
????對象list_1就是一個list蠢莺,我們可以使用索引來訪問list中的每個元素,Python中的索引是從0開始計算的:
>>> list_1[0]
'one'
>>> list_1[2]
?'three'
????也可以倒著訪問list中的每個對象:
>>> list_1[-1]
?'three'
????在往list中添加對象時可以使用append方法:
>>> list_1.append('four')
>>> list_1
['one', 'two', 'three','four']
[if !supportLineBreakNewLine]
[endif]
????想要刪除list中的某個對象可以使用pop方法:
>>> list_1.pop(1)
?'two'
>>> list_1
['one', 'three']
[if !supportLineBreakNewLine]
[endif]
????list 也可以作為單個元素包含在另一個list中:
>>>player=['Curry','Leonard']
>>> NBAplayer=['Westbrook', 'Harden',palyer,'Durant']
[if !supportLineBreakNewLine]
[endif]
????再來看Python的另一種重要的數(shù)據(jù)類型:tuple(元組)耐齐。tuple和list十分類似浪秘,不同的是tuple是以括號()形式存在的,且tuple一旦初始化后就不能像list一樣可以隨意修改了埠况。
>>> tuple_1 = ('one', 'two', 'three')
>>> tuple_1
('one', 'two', 'three')
????tuple具有和list一樣的對象元素訪問功能耸携,這里不再贅述。需要注意的是辕翰,因為tuple元素是不可變對象夺衍,相應的也就沒有和list一樣的append、pop等修改元素的方法喜命。
????最后看Python中比較特殊的一種數(shù)據(jù)類型:dict(字典)沟沙。字典,顧名思義壁榕,肯定是具有強大的數(shù)據(jù)查詢功能了矛紫。dict在其他程序語言中叫做map,具有key-value(鍵-值)的存儲功能牌里,看下面的示例:
>>> dict_1={'one':1, 'two':2}
>>> dict_1['one']
1
????除了在創(chuàng)建dict時指定各元素的key-value之外颊咬,還可以通過key來單獨指定值放入:
>>> dict_1 ['three'] = 3
>>> dict_1['three']
3
????dict查找或插入數(shù)據(jù)的速度極快,但也占用了大量的內存牡辽,這一點正好和list相反喳篇。另一種和dict類似的數(shù)據(jù)類型叫做set(集合),它是一組key的集合但沒有保存value态辛,這里就不做介紹了麸澜。
>>>>
Python 編程基礎
????今天我主要介紹if-else條件判斷以及for和while的循環(huán)語句。條件判斷和循環(huán)作為任一編程語言的基礎課有必要在此重點強調說明奏黑。先看Python中的if-else條件判斷語句:
score = 66
if score >= 60:
?print('The scores arequalified!')
else:
?print('The scores are unqualified!')
????我們也可以用elif做更細致的條件判斷:
score = 66
if score >= 90:
?print('
Excellent!')
elif 80<=points<90:
?print('Fine!')
elif 60<=points<80:
?print('
Secondary!')
else:
?print('
Unqualified!')
[if !supportLineBreakNewLine]
[endif]
????Py循環(huán)語句和其他語言原理一致炊邦,這里不再詳細展開编矾,就以常見的高斯求和使用for和while循環(huán)為例來展示Python的循環(huán)功能。
????for循環(huán):
sum=0
for x in range(101):
?sum = sum + x
print(sum)
5050
????while循環(huán):
sum=0
n = 99
while n > 0:
?sum = sum + n
?n = n - 2
print(sum)
5050