1. 程式人生 > >python程式設計基礎2:python資料型別

python程式設計基礎2:python資料型別

從一個簡單的例子開始:輸入5個數,按從大到小輸出。你怎麼做?

其實可以按照昨天的一個例題那樣子做,但是資料較多,繁瑣且容易出錯。但是使用python的列表(list)資料型別就不會這樣了。

1、列表

先通過如下的例子瞭解list的一些基本的操作:

>>> a=[1,2,3]
>>> b=[2,3,4]   這就是列表
>>> a+b
[1, 2, 3, 2, 3, 4]
>>> a.append(b)
>>> a
[1, 2, 3, [2, 3, 4]]   這也是列表

>>> a.extend(b)
>>> a
[1, 2, 3, [2, 3, 4], 2, 3, 4]
>>> a=a+b
>>> a
[1, 2, 3, [2, 3, 4], 2, 3, 4, 2, 3, 4]
可見   a=a+b一樣的可以實現  a.extend(b)的效果。同時通過上面的例子你也應該知道a.extend(b)和a.append(b)的區別了(這個在機器學習實戰38頁也用到了

)下面我們來實現上面的例子:輸入5個值,按順序輸出。

程式碼:

inputlist=[]
for i in range(5):
    num=input( 'please input the'+str(i+1)+'number:')
    inputlist=inputlist+[num]
print 'the list is:',inputlist
inputlist.sort()
print 'the sorted list is :',inputlist

結果:

please input the1number:34
please input the2number:56
please input the3number:26
please input the4number:78
please input the5number:35
the list is: [34, 56, 26, 78, 35]
the sorted list is : [26, 34, 35, 56, 78]

是不是很簡單。特別是這一行inputlist=inputlist+[num] 其中num本來就是一個數字,但是直接加上一個[]符號就將他轉化為list了非常的方便。

另外,知道下面的不同:

>>> a=[1,'3',2]
>>> a[1]
'3'
>>> print a[1]
3

還有一個insert,del,以及幾個函式:cmp(),sorted(),reversed()等

>>> a
[1, 'iker']
>>> a.insert(1,'peng')

>>> len(a)
3
>>> sorted(a)
[1, 'iker', 'peng']

>>> a
[1, 'peng', 'iker']

>>> sorted(a,reverse=True)
['peng', 'iker', 1]
>>> a
[1, 'iker', 'peng']

2、元組

元組和list非常的相似,區別在於元組中的資料一旦定義就不能更改,所以也就沒有增加和刪除的屬性了。所以元組更加的安全。並且速度也是比較快的。

元組的特色:

檢索元素:

>>> a=(1,'iker',[2,3])
>>> a
(1, 'iker', [2, 3])
>>> type(a)
<type 'tuple'>
>>> a.count('iker')
1
>>> b=a.count('peng')
>>> b
0

返回索引:

>>> a.index(1)
0

賦多值:

>>> x,y,z=a
>>> x
1
>>> y
'iker'
>>> z
[2, 3]

3.字典使用{}定義的一種資料型別,能夠設定鍵值以及它所指向的值。

>>> a={'a':'answer',1:'iker','peng':'iker'}
>>> a['a']
'answer'
>>> a[1]
'iker'
>>> 'iker' in a
False                 不能找到值是否存在,只能找相應的鍵值。
>>> 'peng' in a