顯示具有 物件導向 標籤的文章。 顯示所有文章
顯示具有 物件導向 標籤的文章。 顯示所有文章

2010年10月22日 星期五

wxPython 筆記 ( event 01 )

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import wx

class MyApp(wx.App):
    def OnInit(self):
        frame=MyFrame(title=u"視窗",pos=(100,150),size=(250,200))
        frame.Show()
        self.SetTopWindow(frame)
        return True


class MyFrame(wx.Frame):
    def __init__(self,title,pos,size):
        wx.Frame.__init__(self,None,-1,title,pos,size) # 備用,使用取代 frame 的 OnInit()

        #建立panel
        panel=wx.Panel(self)
        #新增一個按鈕並把它加到panel裡面
        button=wx.Button(panel,label=u"按鍵_1",pos=(25,25),size=(80,50))
        #新增另一個按鈕並把它加到panel裡面
        button_2=wx.Button(panel,label=u"按鍵_2",pos=(25,100),size=(80,50))

        # 建立事件監聽 #############################################################

        # 攔截「右上角 x 之視窗關閉鍵   wx.EVT_CLOSE」,轉向 OnCloseWin,得 :確定要關閉程式
        self.Bind(wx.EVT_CLOSE,self.OnCloseWin)

        #攔截「按 button 鍵   wx.EVT_BUTTON 」,轉向 OnClick ,得出 : 你按了 '按鍵1'
        self.Bind(wx.EVT_BUTTON,self.OnClick_1,button)

        #攔截「按 button 鍵   wx.EVT_BUTTON 」,轉向 OnClick ,得出 : 你按了 '按鍵1'
        self.Bind(wx.EVT_BUTTON,self.OnClick_2,button_2)

    #定義按鈕案下的函數  
    def OnClick_1(self,event):
        wx.MessageBox(u"你按了 '按鍵_1' ",u"提示訊息")

    def OnClick_2(self,event):
        wx.MessageBox(u"你按了 '按鍵_2' ",u"提示訊息")
      
    #定義按下關閉視窗(右上X)的函數
    def OnCloseWin(self,event):
        dlg=wx.MessageDialog(None,u"確定要關閉程式?",u"提示訊息",wx.YES_NO)
      
        #按下YES才會關閉視窗
        if dlg.ShowModal()==wx.ID_YES:
            self.Destroy()


if __name__=="__main__":
    app = MyApp()
    app.MainLoop()

2009年11月3日 星期二

Python筆記: 序列 Sequences (索引 index , 分片 slice )

  
  
1- 序列 Sequences 只是個名稱(溝通用途)。重點是它的兩個功能:
 
  1-1 索引 index 用來指示位置,取出特定項目內容。
 
  1-2 分片 slice 直接取出取出特別部份。

2- 序列 Sequences 的功能可用於「文字」。看下例:

   >>> sequ='abcdefg' # 建立變數

   >>> sequ[0] # 索引 index
   'a'
   
   >>> sequ[1]
   'b'
   
   >>> sequ[-1]
   'g'
   
   >>> sequ[3:]
   'defg'

   >>> sequ[3:5]
   'de'

   >>> sequ[:5]
   'abcde'

   >>> sequ[:-2]
   'abcde'

   >>> new_work=sequ[3:] # 將分片內容轉存入 new_work
   >>> new_work
   'defg'
       
3- 序列 Sequences 的功能亦可用於 LIST 及 TUPLE。看下例:

   >>> KK=(11,12,13) # 建立 TUPLE
   >>> KK[-1] # 索引
   13

   >>> hh=KK[-1] # 分片,將特定內容存入 hh
   >>> hh
   13
   
   >>> gg=[hh,123456789,'python'] # 將分片內容轉存入 list
   >>> gg
   [13, 123456789, 'python']
   
   >>> gg[1]=1 # LIST 內容是可變的
   >>> gg
   [13, 1, 'python']
   
   >>> gg[0]=gg[0]*3
   >>> gg
   [39, 1, 'python']
   
4- 我們可以說 list 與 tuple 基本相同,tuple 只是用作預設變數。
 
5- 序列 Sequences 本質就是將 list 與 tuple 混合使用。
 
 
 
 
  
  
  
  
  

2009年11月2日 星期一

Python筆記: 元組 TUPLE 基本認識

 
 
元組 TUPLE 是一個「對象 object」,它的基本特徵是:
 
1- 以 ( ) 作標號,如 ( 'a','b','c',1,2,3 ) 。
 
2- TUPLE 的內容不可改變,是列表 LIST 的唯讀版。
 
元組 TUPLE 的相關資料有:
 
  Python筆記:元組(Tuple)
 
  Python筆記:元組(Tuple) (二)

  [Python 學習筆記] 5: List & Tuple

 

 
  

2009年10月31日 星期六

(轉載)Python 的 self

以下是一篇轉載文,偶然在網上找來的。它解決了我幾天來對 self 的疑惑。


原文:Python 的 self


初學 Python,有個令我很頭大的地方是 self 對 class variable 的修飾。要加不加 self,傻傻分不清楚......。原先習慣了 C++ 中的 variable scope,換個語言就躺平瞭。所幸有股溝的協助,把股來的結果整理一下;依我目前為止的理解,下面是 C++ 和 Python 2.5 等價的程式碼:

   C++

   int globalVar = 5;

   class Class
   {
   public:
     Class() { attribute = 30; }
     void func() {
       int localVar = 20;
       localVar = attribute;
     }

   int attribute;
   static int staticVar;
   };

   int Class::staticVar = 10;

   Python

   globalVar = 5

   class Class:
     staticVar = 10
     def __init__(self):
       self.attribute = 30
     def func(self):
       localVar = 20
       localVar = self.attribute

   Class.staticVar = 10

總之,變數若加了 self,就成了 instance 的 attribute,可以在同一個 instance 內跨 method 存取。如果沒加的話,就被限制在定義時的 scope 裡。

至於 member function 的 self argument,和 C++ 的 this 一樣,是用來區別呼叫的 instatnce 的。

寫了一天的 Python,有股衝動想從 C/C++ 跳槽,永世不再返......


********** 2009-11-04 12:50 補充 **********

參考了《電腦做什麼事》的例子,self 的用法更明白。



  
  
   

2009年10月30日 星期五

Python筆記: 列表 LIST 基本認識

列表 LIST 也是一個「對象 object」,它的基本特徵是:

1- 以 [ ] 作標號,如 [ 'a','b','c',1,2,3] 。

2- LIST 是可變的,即可以增加、刪除和搜尋。參考。

3- LIST 也有「方法 method」。參考。

4- LIST 可以和 fuction 混用。參考。
  
4- LIST 和 tuples、dictionary、Sequences 有密切關係。如下例:



>>> li
['pp', 'two', 5, 11]

>>> aa='my name'
>>> li+=[aa]
>>> li
['pp', 'two', 5, 11, 'my name']

>>> zoo=(aa, 'bb')
>>> zoo
('my name', 'bb')

>>> aa=zoo
>>> zoo
('my name', 'bb')

>>> aa
('my name', 'bb')

>>> rr={ aa:li}
>>> rr
{('my name', 'bb'): ['pp', 'two', 5, 11, 'my name']}

  
  
   
   

2009年10月29日 星期四

筆記:Python 的 Class (二) Class、object、instantiation

  

一、結構

  Class A ----> object 1 ----> instantiation
      |
      |--> object 2 ----> instantiation
      |
      |--> object 3 ----> instantiation
      |
      |--> ............................

  簡單講,一個 Class 同時可以有多個 object,
  而 object 必須 instantiation 才可運用。

二、instantiation(實例化)

  實例化有兩個方向,一係設定 attribute (屬性),如 attr.class ,
  另一個係 method(方法),即係寫成 function (函數)。

  如下例:

>>> class book2:
    " 這是一個測試, class book"
    author="storylai"
    name="Hello, Python !"
    price=500
      def show(self):
         print self.author
         print self.name
         print self.price

>>> book2().show()
storylai
Hello, Python !
500

三、 method(方法)

  在上例中,凡使用method(方法)時,必須採用如 def() 函數作定義,
  唯一不同是必須包含參數 self 。

  因此,使用 method 中的屬性時,必須寫成 self.attris 。

  參數 self 的出現,是區分「公用」或「私有」的 namespace 命名空間,
  這樣既可對特定的屬性作出保護,又可以區分不同 class 但同名的屬性或
  方法。
 
  上例中,同一 class 中的 author 雖然被視為「公用」,但仍只限於同一
  class 內使用。而在 def 內應用時,亦要加上 self.xxxx ,以避免誤用。



  
  
  

2009年10月28日 星期三

筆記:Python 的 Class (一) 基本認識

  
Class 類 -> Object 對像
        |
     (1) type:各種文字、數字或 Tuple 等數據形式。
     (2) attribute 屬性: attr.class。
     (3) scope 域:定義時可包念多個 namespace 命名空間。
     (4) namespace 命名空間:在記憶體所佔的位址。
        |
        |---> (5) instantiation 實例化: 方法,函數, 實例
        |---> (6) attribute references 屬法:內部變量, 數據儲存
  
例一 attribute references 屬法 內部變量, 數據儲存

>>> class book:
    " 這是一個測試, class book"
    author="storylai"      # (1)
    name="Hello, Python !"    # (1)
    price=500         # (2)
  
>>> book              # (4)

>>> print book
__main__.book            # __main__ 表示是主程式
>>> a=book()
>>> a.author
'storylai'
>>> a.name
'Hello, Python !'
>>> a.price
500
 
例二 instantiation 實例化 方法 函數, 實例
 
>>> class book2:
    " 這是一個測試, class book"
    author="storylai"
    name="Hello, Python !"
    price=500
      def show(self):
         print self.author
          print self.name
          print self.price

>>> book2().show()
storylai
Hello, Python !
500
  
  
  

2009年10月21日 星期三

Import Module (一)

1- 建立 test02.py ,內容如下:

class aaa:
  i="abc"
  def __init__(self):
    self.i="xwyz"
  def baby(self):
    print "My name is BABY !"

2- 測試

>>> import test02
>>> print aaa.i

結果是出錯。

Traceback (most recent call last):
File "", line 1, in
print aaa.i
NameError: name 'aaa' is not defined

3- 加入 test02 的前置名

>>> print test02.aaa.i
abc

4- 以變數取代 test02 的前置名

>>> aa=test02
>>> aa.aaa.i
'abc'

5- 測試 def __init__(self)

>>> aa.aaa().i
'xwyz'

6- 測試 baby(self)

>>> aa.aaa().baby()
My name is BABY !
  
  
  
  

Python 的 字典 Dictionary (二)

1- 建立一個 Dictionary

>>> a = {1:"a", 2:"b"}


2- 讀出 Dictionary 中 1 的索引值

>>> a[1]
'a'

3- 用變數 mm 取代索引 1 的值

>>> mm=1
>>> a[mm]
'a'

4- 變更索引 1 的值為 99

>>> a[1]=99
>>> a[1]
99
>>> a
{1: 99, 2: 'b'}

5- 列出 a 的所有索引

>>> a.keys()
[1, 2]

6- 以 list [] 列出 a 的所有索引

>>> a.items()
[(1, 99), (2, 'b')]

 
  
  

[Python 學習筆記] 5: List & Tuple

上網時看到的一篇,簡明清楚,留下來日後參考。

http://www.rainsts.net/article.asp?id=380


[ 2006-12-13 17:14:52 | 作者: yuhen ]


列表(List) : 類似於 .NET ArrayList / List。

元組(Tuple) : 列表的唯讀版。

1. 轉換

我們可以使用 list() / tuple() 函數在列表和元組之間進行轉換。

>>> a = [1, 2, 3]
>>> b = tuple(a)
>>> b
(1, 2, 3)
>>> c = list(b)
>>> c
[1, 2, 3]


這兩個函數接受字串參數時候比較有意思。

>>> list("abc")
['a', 'b', 'c']
>>> tuple("abc")
('a', 'b', 'c')


2. 運算符操作

列表支援運算符操作。

>>> [1, 2] * 2
[1, 2, 1, 2]
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]


3. in / not in

可以使用 in / not in 來判斷是否包含某個元素。

>>> a = [1, 2, 3]
>>> 1 in a
True
>>> 444 in a
False
>>> 444 not in a
True
>>> b = (1, 2, 3)
>>> 1 in b
True


4. range()

我們還可以使用 range() 函數獲得一個整數列表,甚至進行運算和添加過濾條件。

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(2, 6)
[2, 3, 4, 5]
>>> [x * 2 for x in range(10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> [x for x in range(10) if x % 2 > 0]
[1, 3, 5, 7, 9]
>>> [x + 1 for x in range(10) if x % 2 > 0]
[2, 4, 6, 8, 10]


5. Slices

和字串一樣,我們可以通過序號或切片進行訪問。

>>> b = (1, 2, 3)
>>> b[1]
2
>>> b[1:]
(2, 3)
>>> b[-1]
3
>>> b = [1, 2, 3]
>>> b[1] = 200
>>> b
[1, 200, 3]


6. 相關方法

基本方法:

>>> a = (1, 2, 3)
>>> len(a)
3
>>> min(a)
1
>>> max(a)
3
>>> a = ["a", "b", "c"]
>>> a.index("b")
1
>>> a += ["b"]
>>> a
['a', 'b', 'c', 'b']
>>> a.count("b")
2
>>> a.insert(1, "sss")
>>> a
['a', 'sss', 'b', 'c', 'b']
>>> a.remove("sss")
>>> a
['a', 'b', 'c', 'b']
>>> a.pop(1)
'b'
>>> a
['a', 'c', 'b']
>>> a.reverse()
>>> a
['b', 'c', 'a']
>>> a.sort()
>>> a
['a', 'b', 'c']
>>> a.extend(["d", "e"])
>>> a
['a', 'b', 'c', 'd', 'e']
>>> a.append(["f", "g"])
>>> a
['a', 'b', 'c', 'd', 'e', ['f', 'g']]


還可以使用 filter() 進行過濾。

>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def divfilter(i):
return i % 2 == 0

>>> filter(divfilter, a)
[0, 2, 4, 6, 8]


上面的代碼還可以簡寫為:

>>> filter(lambda i: i % 2 == 0, range(10))
[0, 2, 4, 6, 8]


當 function 參數為 None 時,可以用來過濾掉空值。

>>> b = ["a", "", [], [1, 2]]
>>> filter(None, b)
['a', [1, 2]]


map() 類似 .NET 中的 Array.Foreach()

>>> map(lambda i: i + 10, range(10))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]


另外,我們還可以使用 reduce() 對元素進行統計。

>>> import operator
>>> reduce(operator.add, range(10))
45
>>> 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
45


zip() 方法可以對兩個或多個列表/元組進行交叉合併。

>>> zip(range(1, 10), ("a", "b", "c", "d"))
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]


[最後修改由 yuhen, 於 2006-12-17 23:25:34]


  
  

Pyhton 的 function 及 list 混用

例一

>>> def fun(arg):
print arg

>>> fun("abcde")
abcde
>>> fun(5678)
5678

------------------------------------------

例二

>>> def fun2(**d):
print d

>>> fun2(a=1,b=2,c=3)
{'a': 1, 'c': 3, 'b': 2}

------------------------------------------

例三

>>> def fun3(n):
pritn n

>>> a=(1,2,3)
>>> fun3(a)
(1, 2, 3)

>>> b=(7,8,9)
>>> fun3(b)
(7, 8, 9)

>>> c=a+b
>>> fun3(c)
(1, 2, 3, 7, 8, 9)

------------------------------------------

例四

>>> n=99
>>> m=100
>>> o=101
>>> d=(n,m,o)
>>> fun3(d)
(99, 100, 101)



  

2009年10月19日 星期一

Python筆記:元組(Tuple) (二)

又重頭看 Python 自身提供的 Python Tutorial 。有兩點要記下來。

以變數形式建立 Tuple

>>> a=12345
>>> b="kkkkk"
>>> m=a,b
>>> m
(12345, 'kkkkk')

再看


>>> f=a,b,6535123.1
>>> f
(12345, 'kkkkk', 6535123.0999999996)
>>> h,j,k=f
>>> h
12345
>>> j
'kkkkk'
>>> k
6535123.0999999996

很好用。

Tuple 有以下的各種基本方法:

append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].

extend(L)
Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.

pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() returns the last item in the list. The item is also removed from the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

index(x)
Return the index in the list of the first item whose value is x. It is an error if there is no such item.

count(x)
Return the number of times x appears in the list.

sort()
Sort the items of the list, in place.

reverse()
Reverse the elements of the list, in place.

  
  

(轉載)Python-字符串操作方法

http://blog.isaysay.cn/show-98-1.html


python字符串


字符串中字符大小寫的變換:


* S.lower() #小寫

* S.upper() #大寫

* S.swapcase() #大小寫互換

* S.capitalize() #首字母大寫

* String.capwords(S)
#這是模塊中的方法。它把S用split()函數分開,然後用capitalize()把首字母變成大寫,最後用join()合併到一起

* S.title() #只有首字母大寫,其餘為小寫,模塊中沒有這個方法


字符串在輸出時的對齊:

* S.ljust(width,[fillchar])
#輸出width個字符,S左對齊,不足部分用fillchar填充,默認的為空格。

* S.rjust(width,[fillchar]) #右對齊

* S.center(width, [fillchar]) #中間對齊

* S.zfill(width) #把S變成width長,並在右對齊,不足部分用0補足


字符串中的搜索和替換:

* S.find(substr, [start, [end]])
#返回S中出現substr的第一個字母的標號,如果S中沒有substr則返回-1。start和end作用就相當於在S[start:end]中搜索

* S.index(substr, [start, [end]])
#與find()相同,只是在S中沒有substr時,會返回一個運行時錯誤

* S.rfind(substr, [start, [end]])
#返回S中最後出現的substr的第一個字母的標號,如果S中沒有substr則返回-1,也就是說從右邊算起的第一次出現的substr的首字母標號

* S.rindex(substr, [start, [end]])

* S.count(substr, [start, [end]]) #計算substr在S中出現的次數

* S.replace(oldstr, newstr, [count])
#把S中的oldstar替換為newstr,count為替換次數。這是替換的通用形式,還有一些函數進行特殊字符的替換

* S.strip([chars])
#把S中前後chars中有的字符全部去掉,可以理解為把S前後chars替換為None

* S.lstrip([chars])

* S.rstrip([chars])

* S.expandtabs([tabsize])
#把S中的tab字符替換沒空格,每個tab替換為tabsize個空格,默認是8個


字符串的分割和組合:

* S.split([sep, [maxsplit]])
#以sep為分隔符,把S分成一個list。maxsplit表示分割的次數。默認的分割符為空白字符

* S.rsplit([sep, [maxsplit]])

* S.splitlines([keepends])
#把S按照行分割符分為一個list,keepends是一個bool值,如果為真每行後而會保留行分割符。

* S.join(seq) #把seq代表的序列──字符串序列,用S連接起來


字符串的mapping,這一功能包含兩個函數:

* String.maketrans(from, to)
#返回一個256個字符組成的翻譯表,其中from中的字符被一一對應地轉換成to,所以from和to必須是等長的。

* S.translate(table[,deletechars])
#使用上面的函數產後的翻譯表,把S進行翻譯,並把deletechars中有的字符刪掉。需要注意的是,如果S為unicode字符串,那麼就不支持 deletechars參數,可以使用把某個字符翻譯為None的方式實現相同的功能。此外還可以使用codecs模塊的功能來創建更加功能強大的翻譯表。


字符串還有一對編碼和解碼的函數:

* S.encode([encoding,[errors]])
#其中encoding可以有多種值,比如gb2312 gbk gb18030 bz2 zlib big5 bzse64等都支持。errors默認值為"strict",意思是UnicodeError。可能的值還有'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 和所有的通過codecs.register_error註冊的值。這一部分內容涉及codecs模塊,不是特明白

* S.decode([encoding,[errors]])


字符串的測試函數,這一類函數在string模塊中沒有,這些函數返回的都是bool值:


* S.startwith(prefix[,start[,end]])
#是否以prefix開頭

* S.endwith(suffix[,start[,end]])
#以suffix結尾

* S.isalnum()
#是否全是字母和數字,並至少有一個字符

* S.isalpha() #是否全是字母,並至少有一個字符

* S.isdigit() #是否全是數字,並至少有一個字符

* S.isspace() #是否全是空白字符,並至少有一個字符

* S.islower() #S中的字母是否全是小寫

* S.isupper() #S中的字母是否便是大寫

* S.istitle() #S是否是首字母大寫的


字符串類型轉換函數,這幾個函數只在string模塊中有:


* string.atoi(s[,base])
#base默認為10,如果為0,那麼s就可以是012或0x23這種形式的字符串,如果是16那麼s就只能是0x23或0X12這種形式的字符串

* string.atol(s[,base]) #轉成long

* string.atof(s[,base]) #轉成float
  
  
  

2009年10月17日 星期六

Python 的 字典 Dictionary (一)

參考自:

http://blog.roodo.com/descriptor/archives/7727261.html
http://sebug.net/local/python/ch09s04.html
http://docs.python.org/tutorial/datastructures.html#dictionaries
http://docs.python.org/tutorial/datastructures.html#looping-techniques

Dictionary 的結構如下:

d = {index_key1 : value1, index_key2 : value2 }。

1- Dictionary 以{ } 宣告結構,index_key 與 value 以「冒號 :」 分開,每組數據再以「逗號 ,」 分隔。

2- Dictionary 數據可以更改。

3- Dictionary 內的 index_key 與 value 可結合 list 及 tuple 的特色,再以變數取代,如下例:

>>> a="first"
>>> a1=12345
>>> b="second"
>>> b1=99999
>>> c="third"
>>> c1=8765
>>> ddd=([(a,a1),(b,b1),(c,c1)])
>>> ddd
[('first', 12345), ('second', 99999), ('third', 8765)]

4- 還有一個超方便的寫入 index_key 與 value 方法,就是用 Sequences (序列) 的特色。如下例:

>>> fg1="apple"
>>> fg2="orange"
>>> names=[ fg1,fg2]
>>> names
['apple', 'orange']

>>> cc1=999
>>> cc2=1024
>>> counts=[cc1,cc2]

>>> dic=dict(zip(names,counts))
>>> dic
{'orange': 1024, 'apple': 999}

>>> dic.items()
[('orange', 1024), ('apple', 999)]
>>> dic.keys()
['orange', 'apple']


5- 在官網的 Python Tutorial 中有以下的賦值例子。

for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe






  

2009年10月16日 星期五

Python筆記:元組(Tuple)

Tupe 的譯法很多,有「序列」及「元組」。我習慣用「元組」。

它與列表(LIST)類似,但有四個顯著的不同。

1- 列表用 [ ] ,元組以 ( ) 做集合符號。

2- 列表有方法(Method),元組沒有。

3- 列表宣告後所有元素可以改變、增刪,元組則不會。

5- 元組可以疊加而不影響其成員。

>>> zoo = ('wolf', 'elephant', 'penguin')
>>> new_zoo = ('monkey', 'dolphin', zoo)
>>> len(new_zoo)
3

>>> print new_zoo
('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))

>>> print (zoo)
('wolf', 'elephant', 'penguin')

>>> print new_zoo[2]
('wolf', 'elephant', 'penguin')

>>> new_zoo[2][2]
'penguin'



   

Python 筆記: 列表 LIST (二)

參考自
http://sebug.net/local/python/ch09s02.html
http://www.pythonclub.org/python-basic/list
http://effbot.org/zone/python-list.htm
http://man.chinaunix.net/develop/python/diveinto_python/odbchelper_list.html


分割一個列表(分片)

li=['a', 'b', 'mpilgrim', 'z', 'example']

例1 li[1:3],由li[1]開始,直至li[3]為止,故只分出 ['b', 'mpilgrim'] 。
例2 li[1:-1],由li[1]開始,直至最後一個li[-1]為止,故分出['b', 'mpilgrim', 'z']
例3 li[0:3] ,由li[0]開始,直至li[3]為止,故分出['a', 'b', 'mpilgrim']


分片縮寫

li=['a', 'b', 'mpilgrim', 'z', 'example']

例4 li[:3],得出 ['a', 'b', 'mpilgrim']
例5 li[3:] ,得出 ['z', 'example']
例6 li[:],得出 ['a', 'b', 'mpilgrim', 'z', 'example']


列表操作符

li = ['a', 'b', 'mpilgrim']

li = li + ['example', 'new']
['a', 'b', 'mpilgrim', 'example', 'new']

li += ['two']
['a', 'b', 'mpilgrim', 'example', 'new', 'two']

li = [1, 2] * 3
[1, 2, 1, 2, 1, 2]


用某个固定值初始化列表

initial_value = 0
list_length = 5
sample_list = [ initial_value for i in range(10)]
sample_list = [initial_value]*list_length
# sample_list ==[0,0,0,0,0]


像我怕打字的人,會以變數取代 LIST 內的「文字變數」,如

>>> li
['pp', 'two', 5]

>>> li+=[11]

>>> li
['pp', 'two', 5, 11]

>>> aa='my name'
>>> li+=[aa]
>>> li
['pp', 'two', 5, 11, 'my name']

  
  

Python筆記: 列表 LIST (一)

參考自
http://sebug.net/local/python/ch09s02.html
http://www.pythonclub.org/python-basic/list
http://effbot.org/zone/python-list.htm
http://man.chinaunix.net/develop/python/diveinto_python/odbchelper_list.html



獲得 LIST 的相關資訊
help(list)

aaa=12345
aList=[ ‘baby’,’tom’,’mary’,aaa]

求 LIST 內的個數
print len(aList)

加入新的元素(放在最後)
aList.append(‘Jackson’)
Print aList[5]

插入新的元素(放在指定位置)
aList.insert(2, "insert")
[ ‘baby’,’tom’,’insert’,’mary’,aaa]

插入相同的元素(放在指定位置)
aList.insert(-1, "insert2")
[ ‘baby’,’tom’,’insert’,’mary’, ‘insert2’,aaa]

LIST 內元素的排序
aList.sort()

讀出 List 內第一個元素
bbb=aList[0]

讀出 List 內最後之一個元素
bbb=aList[-1]

讀出列表內所有元素
for element in sample_list:
print(element)

搜索列表
Li=['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

li.index("example"),得出5。
li.index("new"),得出2。
li.index("c"),沒有 c ,出錯誤訊息。

刪除 List 內第一個元素
del.aList[0]
aList.remove[3]
aList.remove[‘insert2’]
aList.pop() 剛除最後一個元素,並顯示於熒幕。


  
  

2008年8月9日 星期六

筆記:物件導向(Object Oriented)(二)

以 python 為例

# -*- coding: utf-8 -*-


class Test001:
# 開一個 class

  def __init__ (self, name, age, gender):
# 開一個函數,它包含name, age, gender 三個屬性
# def 前要空四格

    self.name = name
    self.age = age
    self.gender = gender
# 就不同屬性賦予不同內容
# 以上三行均要空四格

C_name= "姚 明"
# 定義 C_name 變數

s = Test001(C_name, 20, "f")
#設 s 變數,重點是 姚明 = C_name = name 屬性

print s

print s.name,s.age,s.gender

print s.name

print s.gender


結果如下:

IDLE 1.2.2
>>> ================================ RESTART ================================
>>>
<__main__.test001>
姚 明 20 f
姚 明
f
>>>

2008年7月31日 星期四

筆記:物件導向(Object Oriented)(一)

物件導向(Object Oriented)簡稱為 OO。

OO={資料定義+操作方法}

1- 以 OO 來建構:

將要做的想清楚,技術上是將:
實體(Instance,要做的事)---------------> 物件(object)


2- 物件(object)是:
欄位 field
方法 method
成員 member


3- 舉個「筆」的例子:

成員 member
---------------------------------------
欄位 field 方法 method
---------------------------------------
種類 (字串 string) count
數量 (整數 init) sum
價格 (整數 init) avg


4- 經過宣告(declare),上面的例子便是一個類別(class)。