Python list范例最基本的運(yùn)算式
Python list范例有不少的人都不知道是怎么回事。其實(shí)這是一個很有趣的東西。也是不少開發(fā)人員迷戀上Python 這門語言的原因之一。下面我們就來詳細(xì)的看看如何進(jìn)行相關(guān)的問題。#t#
通常,程序員愛上Python是因?yàn)樗茉黾由a(chǎn)力。由于沒有編譯過程,編輯-測試-調(diào)試周期相當(dāng)快。調(diào)試Python程序很簡單:一個錯誤永遠(yuǎn)不會導(dǎo)致一個段錯誤。當(dāng)解釋器發(fā)現(xiàn)錯誤時,它就引發(fā)一個異常。當(dāng)程序沒有捕捉到異常,解釋器就打印一個堆棧跟蹤。一個源碼級調(diào)試器允許我們檢查局部和全局變量,計算表達(dá)式,設(shè)置斷點(diǎn),單步跟蹤等等。調(diào)試器是用Python寫的,這證明了Python的能力。另外,最快的調(diào)試程序的方法是增加幾條打印語句:快捷的編輯-測試-調(diào)試周期使得這個簡單的辦法十分有效。
Python list范例基本的運(yùn)算式
我們直接切入正題,直接簡單的教你使用 Python。 我假設(shè)讀者己有其它語言的基礎(chǔ),可以直接切入語法重點(diǎn)。
- 1 a = 0
- 2 b = 7
- 3 aa = a + 1
- 4 a = b * a
- 5 print a
- 結(jié)果顯示 : 7
上面就是 python 的簡單例子,相信如果你學(xué)過其它的語言(如 C/C++, Java),就能很容易的了解。
- A+B A 加 B
- A-B A 減 B
- A*B A 乘 B
- A/B A 除 B
- A%B 取 A/B 的馀數(shù)(如 8 % 3 == 2)
- -A 取 A 的反數(shù)( 若 A == 7, -A == -7)
- String
- 1 a = 'hello'
- 2 b = "world"
- 3 c = a + ' ' + b + '!!'
- 4 print c
結(jié)果顯示 : hello world!!
string 可以使用 ' or " 符號括起來表示。在行 3,是合并四個 string object 的例子, 將四個 string 依順連接成單一的 string。
- 1 a = '%s=%d' % ('test', 16)
- 2 print a
結(jié)果顯示 : test=16
類似於 C/C++ 的 printf 或 sprintf,在行 1,python 提供 string format 的功能。 字串 '%s=%d' 指定 string 的 format,而後在字串後接著 % 然後是 format 的參數(shù), 這些參數(shù)會依序取代 format 里的 %s 和 %d。%s 代表要取代字串,%d 則是取代成整數(shù)。
- a = 'This is a rather long string containing\n\
- several lines of text just as you would do in C.\n\
- Note that whitespace at the beginning of the line is\
- significant.\n'
string 可以延伸到數(shù)行,但在每一行的最後必需要有escape \ 以忽略掉 newline。 另外也可以使用 """ 或 '''
- a = '''This is a rather long string containing
- several lines of text just as you would do in C.
- Note that whitespace at the beginning of the line is
- significant.'''
使用 ''' 或 """ 就不需要在每一行結(jié)數(shù)時 escape,但 newline 會被包含入 string 內(nèi)容。
- List
- 1 a = []
- 2 a[0] = 'aoo'
- 3 a[1:3] = [10, 11]
- 4 b = [1, 2, 3, 'foo']
- 5 print a, b, b[:3], b[1:]
結(jié)果顯示 : [9, 10, 11] [1, 2, 3, 'foo'] [1, 2, 3] [2, 3, 'foo']
上面是Python list范例的使用。list 是一個 sequence data type, 類於 C/C++ 的 array, 但 array 是 fixed length 而 list 不是, 其長度是可以隨時改變的。行 1 就 bind a 為一個空的 list。 行 2 則指定 index 0 為 'aoo' string object。行 3 為 list 的 slice 的使用范例。 將 index 1 和 index 3 之間的 item(index 1 和 2) 代換成 10 和 11。行 5 的 b[:3] 則相當(dāng)於 b[0:3], 而 b[1:] 相當(dāng)於 b[1:4]。list 內(nèi)的 item 不需是相同的 type, 如上例在一個 list object 里可以同時包含整數(shù)和 string 不同 type 的 item。