@貳拾貳畫生
感謝?簡明Python教程
輸入輸出
輸入:raw_input
string = raw_input('Enter something:')
輸出:print
s = 'aaa'
i = 1
print string; print 's = %s, i = %d', (s, i)
--------------------------------------------------------
字符串
單引號’ 雙引號” 或三引號’’’ “”"?三引號指示一個(gè)多行的字符串如
‘’'fdalkjflksajfkl
fdafdsa
fda’''
--------------------------------------------------------
字符串中轉(zhuǎn)義字符?\
自然字符串,指示某些不需要如轉(zhuǎn)義符那樣的特別處理的字符串,字符串前加r或R
r”Newlines are indicated by \n"
Unicode字符串:前加u或U
u”This is a Unicode string"
--------------------------------------------------------
級連字符串
兩個(gè)字符串按字面意義相鄰放著
‘What\’s?’ ‘your name?’
會被自動轉(zhuǎn)成
“What’s your name?”
--------------------------------------------------------
多個(gè)物理行寫一個(gè)邏輯行
s = ’This is a string. \
This continues the string.'
print s
輸出為:This is a string. This continues the string.
同理
print \
i
等同于
print i
--------------------------------------------------------
#if else 語句
number = 23
? ? ? ?guess =int(raw_input('Enter an integer : '))
if guess == number:
? ? ? print 'Congratulations, you guessed it.'
? ? ? print "(but you do not win any prizes!)"
elif guess < number:
? ? ? print 'No, it is a little higher than that'
else:
? ? ? print 'No, it is a little lower than that'
print 'Done'
--------------------------------------------------------
# while語句
number =23
running =True
while running:
? ? ? guess = int(raw_input('Enter an integer : '))
? ? ? if guess == number:
? ? ? ? ? ? print 'Congratulations, you guessed it.'
? ? ? ? ? ? running =False
? ? ? elif guess < number:
? ? ? ? ? ? print 'No, it is a little higher than that'
? ? ? else:
? ? ? ? ? ? print 'No, it is a little lower than that'
else:
? ? ?print 'The while loop is over.'
print 'Done'
--------------------------------------------------------
break 語句
while True:
? ? ? s = raw_input('Enter something : ')
? ? ? if s == 'quit':
? ? ? ? ? ? break
? ? ? print 'Length of the string is', len(s)
print 'Done'
--------------------------------------------------------
continue 語句
continue語句被用來告訴Python跳過當(dāng)前循環(huán)塊中的剩余語句,然后繼續(xù)進(jìn)行下一輪循環(huán)。
while True:
? ? ? s = raw_input('Enter something : ')
? ? ? if s == 'quit':
? ? ? ? ? ? break
? ? ? if len(s) <3:
? ? ? ? ? ?continue
? ? ? print 'Input is of sufficient length'
輸出結(jié)果為:
Enter something : a
Enter something : 12
Enter something : abc
Input is of sufficient length
Enter something : quit
--------------------------------------------------------
函數(shù)用?def 關(guān)鍵字來定義
def printMax(a, b):
? ? ? if a > b:
? ? ? ? ? ? ?print a, ' is maximum'
? ? ? else:
? ? ? ? ? ? print b, ' is maximum'
print Max(3,4)
x =5
y =7
print Max(x, y)
輸出:
4 is maximum
7 is maximum
--------------------------------------------------------
使用 global 定義全局變量
def func():
? ? ? global x
? ? ? print 'x is', x
? ? ? x = 2
? ? ? print 'Changed local x to', x
x = 50
func()
print 'Value of x is', x
輸出:
x is 50
Changed global x to 2
Value of x is 2
--------------------------------------------------------
可選的默認(rèn)參數(shù)
def say(message, times = 1):
? ? ? print message * times
say('Hello')
say('World', 5)
輸出:
Hello
WorldWorldWorldWorldWorld
注意:只有在形參表末尾的那些參數(shù)可以有默認(rèn)參數(shù)值,即你不能在聲明函數(shù)形參的時(shí)候,先聲明有默認(rèn)值的形參而后聲明沒有默認(rèn)值的形參。例如,def func(a, b=5)是有效的,但是def func(a=5, b)是無效的。
--------------------------------------------------------
關(guān)鍵參數(shù)
def func(a, b=5, c=10):
? ? ? print 'a is ', a, ' and b is ', b, ' and c is ', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
輸出:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
--------------------------------------------------------
函數(shù)返回
def maximum(x, y):
? ? ? if x > y:
? ? ? ? ? ? return x
? ? ? else:
? ? ? ? ? ? return y
print maximum(2,3)
輸出:
3
注意:沒有返回值的return語句等價(jià)于return None。None是Python中表示沒有任何東西的特殊類型。例如,如果一個(gè)變量的值為None,可以表示它沒有值。
--------------------------------------------------------
使用DocStrings
def printMax(x, y):
? ? ? ?'''Prints the maximum of two numbers.
? ? ? The two values must be integers.'''
? ? ? x = int(x)
? ? ? y = int(y)
? ? ? if x > y:
? ? ? ? ? ? print x, 'is maximum'
? ? ? else:
? ? ? ? ? ? print y,'is maximum'
print Max(3,5)
print printMax.__doc__
輸出:
5 is maximum
Prints the maximum of two numbers.
The two values must be integers.
DocStrings 也適用于模塊和類。
--------------------------------------------------------
模塊
模塊的文件名必須以 .py 為擴(kuò)展名
使用?sys 模塊
import sys
print 'The command line arguments are:'
? ? ? for i in sys.argv:
? ? ? ? ? ? print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'
輸出
The command line arguments are:
we
are
arguments
The PYTHONPATH is ['/home/swaroop/byte/code', '/usr/lib/python23.zip',
'/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2',
'/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload',
'/usr/lib/python2.3/site-packages', '/usr/lib/python2.3/site-packages/gtk-2.0']
sys模塊包含了與Python解釋器和它的環(huán)境有關(guān)的函數(shù)。
腳本的名稱總是sys.argv列表的第一個(gè)參數(shù)。所以,在這里,'using_sys.py'是sys.argv[0]、'we'是sys.argv[1]、'are'是sys.argv[2]以及'arguments'是sys.argv[3]
--------------------------------------------------------
字節(jié)編譯的.pyc文件
輸入一個(gè)模塊相對來說是一個(gè)比較費(fèi)時(shí)的事情,所以Python做了一些技巧,以便使輸入模塊更加快一些。一種方法是創(chuàng)建字節(jié)編譯的文件,這些文件以.pyc作為擴(kuò)展名。字節(jié)編譯的文件與Python變換程序的中間狀態(tài)有關(guān)(是否還記得Python如何工作的介紹?)。當(dāng)你在下次從別的程序輸入這個(gè)模塊的時(shí)候,.pyc文件是十分有用的——它會快得多,因?yàn)橐徊糠州斎肽K所需的處理已經(jīng)完成了。另外,這些字節(jié)編譯的文件也是與平臺無關(guān)的。所以,現(xiàn)在你知道了那些.pyc文件事實(shí)上是什么了。
--------------------------------------------------------
from..import語句
如果你想要直接輸入argv變量到你的程序中(避免在每次使用它時(shí)打sys.),那么你可以使用from sys import argv語句。如果你想要輸入所有sys模塊使用的名字,那么你可以使用from sys import *語句。這對于所有模塊都適用。一般說來,應(yīng)該避免使用from..import而使用import語句,因?yàn)檫@樣可以使你的程序更加易讀,也可以避免名稱的沖突。
--------------------------------------------------------
模塊的__name__
每個(gè)模塊都有一個(gè)名稱,在模塊中可以通過語句來找出模塊的名稱。這在一個(gè)場合特別有用——就如前面所提到的,當(dāng)一個(gè)模塊被第一次輸入的時(shí)候,這個(gè)模塊的主塊將被運(yùn)行。假如我們只想在程序本身被使用的時(shí)候運(yùn)行主塊,而在它被別的模塊輸入的時(shí)候不運(yùn)行主塊,我們該怎么做呢?這可以通過模塊的__name__屬性完成。
if __name__ == '__main__':
? ? ? print 'This program is being run by itself'
else:
? ? ? print 'I am being imported from another module'
輸出:
This program is being run by itself
>>> import using_name
I am being imported from another module
--------------------------------------------------------
創(chuàng)建及引用模塊
創(chuàng)建自己的模塊:
#Filename: mymodule.py
def sayhi():
? ? ? print 'Hi, this is mymodule speaking.'
version ='0.1'
在與該模塊的同等目錄下
import mymodule
mymodule.sayhi()
print 'Version ', mymodule.version
輸出:
Hi, this is mymodule speaking.
Version 0.1
--------------------------------------------------------
dir() 函數(shù)
用來列出模塊定義的標(biāo)識符。標(biāo)識符有函數(shù)、類和變量
如上例,執(zhí)行
?dir(mymodule)
輸出:
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'sayhi', 'version']
如果不給?dir 函數(shù)傳遞參數(shù),默認(rèn)地,它會返回當(dāng)前模塊的屬性列表。
--------------------------------------------------------
Python 中有三種內(nèi)建的數(shù)據(jù)結(jié)構(gòu):列表、元組和字典。
--------------------------------------------------------
列表
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have ', len(shoplist), ' items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
? ? ? print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist
print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist
輸出:
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']
--------------------------------------------------------
元組
元組和列表十分類似,只不過元組和字符串一樣是不可變的,即你不能修改元組。
zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of animals in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]
輸出:
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
有0個(gè)項(xiàng)目的元組:myempty = ()
有1個(gè)項(xiàng)目的元組:singleton = (1, )
--------------------------------------------------------
元組與打印語句
age =22
name = 'Swaroop'
print ' %s is %d years old.’ % (name, age) #此句等同:print name, ‘ is ‘, age, ‘ years old.'
print 'Why is %s playing with that python?' % name
輸出:
Swaroop is 22 years old
Why is Swaroop playing with that python?
--------------------------------------------------------
字典
ab = { ? 'Swaroop' ?: ?'swaroopch@byteofpython.info',
? ? ? ? ? ? ? 'Larry' ? ? : ?'larry@wall.org',
? ? ? 'Matsumoto' ? : ?'matz@ruby-lang.org',
? ? ?'Spammer' ? ? ? : ?'spammer@hotmail.com'
}
print "Swaroop's address is %s" % ab['Swaroop']
ab['Guido'] = 'guido@python.org'
del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
? ? ? print 'Contact %s at %s' % (name, address)
if 'Guido' in ab:
print "\nGuido's address is %s" % ab['Guido']
輸出:
Swaroop's address isswaroopch@byteofpython.info
There are 4 contacts in the address-book
Contact Swaroop atswaroopch@byteofpython.info
Contact Matsumoto atmatz@ruby-lang.org
Contact Larry atlarry@wall.org
Contact Guido atguido@python.org
Guido's address isguido@python.org
--------------------------------------------------------
序列
序列的兩個(gè)主要特點(diǎn)是索引操作符和切片操作符。索引操作符讓我們可以從序列中抓取一個(gè)特定項(xiàng)目。切片操作符讓我們能夠獲取序列的一個(gè)切片,即一部分序列。
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'Item 0 is ', shoplist[0]
print 'Item 1 is ', shoplist[1]
print 'Item 2 is ', shoplist[2]
print 'Item 3 is ', shoplist[3]
print 'Item -1 is ', shoplist[-1]
print 'Item -2 is ', shoplist[-2]
# Slicing on a list
print 'Item 1 to 3 is ', shoplist[1:3]
print 'Item 2 to end is ', shoplist[2:]
print 'Item 1 to -1 is ', shoplist[1:-1]
print 'Item start to end is ', shoplist[:]
輸出:
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]
輸出:
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
--------------------------------------------------------
參考
當(dāng)你創(chuàng)建一個(gè)對象并給它賦一個(gè)變量的時(shí)候,這個(gè)變量僅僅參考那個(gè)對象,而不是表示這個(gè)對象本身!也就是說,變量名指向你計(jì)算機(jī)中存儲那個(gè)對象的內(nèi)存。這被稱作名稱到對象的綁定。
print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object
print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0]
print 'shoplist is', shoplist
print 'mylist is', Myles
輸出:
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']
注意:如果你想要復(fù)制一個(gè)列表或者類似的序列或者其他復(fù)雜的對象(不是如整數(shù)那樣的簡單對象),那么你必須使用切片操作符來取得拷貝。如果你只是想要使用另一個(gè)變量名,兩個(gè)名稱都參考同一個(gè)對象,那么如果你不小心的話,可能會引來各種麻煩。
--------------------------------------------------------
更多字符串方法
name = 'Swaroop' # This is a string object
if name.startswith('Swa'):
? ? ? print 'Yes, the string starts with "Swa"'
if 'a' in name:
? ? ? print 'Yes, it contains the string "a"'
if name.find('war') !=-1: #返回-1表示找不到子字符串
? ? ? print 'Yes, it contains the string "war"'
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)
輸出:
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China
--------------------------------------------------------
類 class
class Person:
? ? ? population = 0
? ? ? def __init__(self, name):
? ? ? ? ? ? ?self.name?= name
? ? ? ? ? ? print '(Initializing %s)' % self.name
? ? ? ? ? ? Person.population += 1
? ? ? def __del__(self):
? ? ? ? ? ? '''I am dying.'''
? ? ? ? ? ? print' %s says bye.' % self.name
? ? ? ? ? ? Person.population -= 1
? ? ? ? ? ? if Person.population == 0:
? ? ? ? ? ? ? ? ? print 'I am the last one.'
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? print 'There are still %d people left.' % Person.population
? ? ? def sayHi(self):
? ? ? ? ? ? '''Greeting by the person.
? ? ? ? ? ? ?Really, that's all it does.'''
? ? ? ? ? ? print 'Hi, my name is %s.' % self.name
--------------------------------------------------------
繼承
class SchoolMember:
? ? ? def __init__(self, name):
? ? ? ? ? ??self.name?= name
? ? ? def tell(self):
? ? ? ? ? ? print 'Name: ' +?self.name
class Teacher(SchoolMember):
? ? ? ?def __init__(self, name, salary):
? ? ? ? ? ? SchoolMember.__init__(self, name)
? ? ? ? ? ? self.salary = salary
? ? ? def tell(self):
? ? ? ? ? ? print 'Salary : %d ' % self.salary
class Student(SchoolMember):
? ? ? def __init__(self, name, marks):
? ? ? ? ? ? SchoolMember.__init__(self, name)
? ? ? ? ? ? self.marks = marks
? ? ? def tell(self):
? ? ? ? ? ? print 'Marks : %d' % self.marks
t = Teacher('Chengjie', 10000)
s = Student('Makai', 99)
members = [t, s]
for member in members:
? ? ? member.tell()
輸出:
Salary : 10000
Marks : 99
--------------------------------------------------------
操作文件 file
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = file('poem.txt', 'w')
f.write(poem)
f.close()
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
? ? ? line = f.readline()
? ? ? if len(line) ==0:# Zero length indicates EOF
? ? ? ? ? ? break
? ? ? print line,
f.close()# close the file
輸出:
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
r:讀模式
w:寫模式
a:追加模式
--------------------------------------------------------
儲存器
Python提供一個(gè)標(biāo)準(zhǔn)的模塊,稱為pickle。使用它你可以在一個(gè)文件中儲存任何Python對象,之后你又可以把它完整無缺地取出來。這被稱為持久地儲存對象。
還有另一個(gè)模塊稱為cPickle,它的功能和pickle模塊完全相同,只不過它是用C語言編寫的,因此要快得多(比pickle快1000倍)。你可以使用它們中的任一個(gè),而我們在這里將使用cPickle模塊。記住,我們把這兩個(gè)模塊都簡稱為pickle模塊。
import cPickle as p
shoplistfile = 'shoplist.data'
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f)# dump the object to a file
f.close()
del shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
輸出:
['apple', 'mango', 'carrot']
--------------------------------------------------------
異常
基本格式:
try:
? ? ? fadfdsafdaf
except EOFError:
? ? ? fdaferewasfsdfas
except:
? ? ? fdafdafwerwe
import sys
try:
? ? ? s = raw_input('Enter something --> ')
except EOFError:
? ? ? print '\nWhy did you do an EOF on me?'
? ? ? sys.exit()
except:
? ? ? print '\nSome error/exception occurred.'
? ? ? # here, we are not exiting the program
print 'Done'
輸出:
Enter something—>(#此處輸入ctrl + d)
Why did you do an EOF on me?
$ pythontry_except.py
Enter something --> Python is exceptional!
Done
--------------------------------------------------------
使用 raise 引發(fā)異常
自定義并異常:
class ShortInputException(Exception):
? ? ? '''A user-defined exception class.'''
? ? ? def __init__(self, length, atleast):
? ? ? ? ? ? Exception.__init__(self)
? ? ? ? ? ? self.length = length
? ? ? ? ? ? self.atleast = atleast
try:
? ? ? s =raw_input('Enter something --> ')
? ? ? if len(s) < 3:
? ? ? ? ? ? raise ShortInputException(len(s), 3)
# Other work can continue as usual here
except EOFError:
? ? ? print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
? ? ? print 'ShortInputException: The input was of length %d, \
? ? ? was expecting at least %d'% (x.length, x.atleast)
else:
? ? ? print 'No exception was raised.'
--------------------------------------------------------
try…finally
finally 后為必定執(zhí)行語句
--------------------------------------------------------
os模塊
這個(gè)模塊包含普遍的操作系統(tǒng)功能。如果你希望你的程序能夠與平臺無關(guān)的話,這個(gè)模塊是尤為重要的。即它允許一個(gè)程序在編寫后不需要任何改動,也不會發(fā)生任何問題,就可以在Linux和Windows下運(yùn)行。一個(gè)例子就是使用os.sep可以取代操作系統(tǒng)特定的路徑分割符。
下面列出了一些在os模塊中比較有用的部分。它們中的大多數(shù)都簡單明了。
os.name字符串指示你正在使用的平臺。比如對于Windows,它是'nt',而對于Linux/Unix用戶,它是'posix'。
os.getcwd()函數(shù)得到當(dāng)前工作目錄,即當(dāng)前Python腳本工作的目錄路徑。
os.getenv()和os.putenv()函數(shù)分別用來讀取和設(shè)置環(huán)境變量。
os.listdir()返回指定目錄下的所有文件和目錄名。
os.remove()函數(shù)用來刪除一個(gè)文件。
os.system()函數(shù)用來運(yùn)行shell命令。
os.linesep字符串給出當(dāng)前平臺使用的行終止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
os.path.split()函數(shù)返回一個(gè)路徑的目錄名和文件名。
>>> os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
os.path.isfile()和os.path.isdir()函數(shù)分別檢驗(yàn)給出的路徑是一個(gè)文件還是目錄。類似地,os.path.existe()函數(shù)用來檢驗(yàn)給出的路徑是否真地存在。
--------------------------------------------------------
特殊的方法
在類中有一些特殊的方法具有特殊的意義,比如__init__和__del__方法,它們的重要性我們已經(jīng)學(xué)習(xí)過了。
一般說來,特殊的方法都被用來模仿某個(gè)行為。例如,如果你想要為你的類使用x[key]這樣的索引操作(就像列表和元組一樣),那么你只需要實(shí)現(xiàn)__getitem__()方法就可以了。想一下,Python就是對list類這樣做的!
下面這個(gè)表中列出了一些有用的特殊方法。如果你想要知道所有的特殊方法,你可以在《Python參考手冊》中找到一個(gè)龐大的列表。
名稱說明
__init__(self,...) ?這個(gè)方法在新建對象恰好要被返回使用之前被調(diào)用。
__del__(self) ?恰好在對象要被刪除之前調(diào)用。
__str__(self) ?在我們對對象使用print語句或是使用str()的時(shí)候調(diào)用。
__lt__(self,other) ?當(dāng)使用小于運(yùn)算符(<)的時(shí)候調(diào)用。類似地,對于所有的運(yùn)算符(+,>等等)都有特殊的方法。
__getitem__(self,key) ?使用x[key]索引操作符的時(shí)候調(diào)用。
__len__(self) ?對序列對象使用內(nèi)建的len()函數(shù)的時(shí)候調(diào)用。
--------------------------------------------------------
列表綜合
通過列表綜合,可以從一個(gè)已有的列表導(dǎo)出一個(gè)新的列表。例如,你有一個(gè)數(shù)的列表,而你想要得到一個(gè)對應(yīng)的列表,使其中所有大于2的數(shù)都是原來的2倍。對于這種應(yīng)用,列表綜合是最理想的方法。
#!/usr/bin/python
# Filename:list_comprehension.py
listone = [2,3,4]
listtwo = [2*i for i in listone if i >2]
print listtwo
輸出
$ pythonlist_comprehension.py
[6, 8]
--------------------------------------------------------
在函數(shù)中接收元組和列表
當(dāng)要使函數(shù)接收元組或字典形式的參數(shù)的時(shí)候,有一種特殊的方法,它分別使用*和**前綴。這種方法在函數(shù)需要獲取可變數(shù)量的參數(shù)的時(shí)候特別有用。
>>> def powersum(power, *args):
... ? ? ? ? ? '''Return the sum of each argument raised to specified power.'''
... ? ? ? ? ? total = 0
... ? ? ? ? ? for i in args:
... ? ? ? ? ? ? ? ?total += pow(i, power)
... ? ? ? ? ? return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100
由于在args變量前有*前綴,所有多余的函數(shù)參數(shù)都會作為一個(gè)元組存儲在args中。如果使用的是**前綴,多余的參數(shù)則會被認(rèn)為是一個(gè)字典的鍵/值對。
--------------------------------------------------------
lambda形式
lambda語句被用來創(chuàng)建新的函數(shù)對象,并且在運(yùn)行時(shí)返回它們。
#!/usr/bin/python
# Filename:lambda.py
def make_repeater(n):
? ? ? return lambdas: s*n #可為多參數(shù),如:?return lambda s1,?s2: ?s1 + s2 +?n
twice = make_repeater(2)
printtwice('word')
printtwice(5)
輸出
$ pythonlambda.py
wordword
10
它如何工作
這里,我們使用了make_repeater函數(shù)在運(yùn)行時(shí)創(chuàng)建新的函數(shù)對象,并且返回它。lambda語句用來創(chuàng)建函數(shù)對象。本質(zhì)上,lambda需要一個(gè)參數(shù),后面僅跟單個(gè)表達(dá)式作為函數(shù)體,而表達(dá)式的值被這個(gè)新建的函數(shù)返回。注意,即便是print語句也不能用在lambda形式中,只能使用表達(dá)式。
--------------------------------------------------------
exec和eval語句
exec語句用來執(zhí)行儲存在字符串或文件中的Python語句。例如,我們可以在運(yùn)行時(shí)生成一個(gè)包含Python代碼的字符串,然后使用exec語句執(zhí)行這些語句。下面是一個(gè)簡單的例子。
>>> exec 'print "Hello World"'
Hello World
eval語句用來計(jì)算存儲在字符串中的有效Python表達(dá)式。下面是一個(gè)簡單的例子。
>>> eval('2*3')
6
--------------------------------------------------------
assert語句
assert語句用來聲明某個(gè)條件是真的。例如,如果你非常確信某個(gè)你使用的列表中至少有一個(gè)元素,而你想要檢驗(yàn)這一點(diǎn),并且在它非真的時(shí)候引發(fā)一個(gè)錯(cuò)誤,那么assert語句是應(yīng)用在這種情形下的理想語句。當(dāng)assert語句失敗的時(shí)候,會引發(fā)一個(gè)AssertionError。
>>> mylist = ['item']
>>> assert len(mylist) >= 1
>>> mylist.pop()
'item'
>>> assert len(mylist) >= 1
Traceback (most recent call last):
? ? ? File "", line 1, in ?
AssertionError
--------------------------------------------------------
repr函數(shù)
repr函數(shù)用來取得對象的規(guī)范字符串表示。反引號(也稱轉(zhuǎn)換符)可以完成相同的功能。注意,在大多數(shù)時(shí)候有eval(repr(object)) == object。
>>> i = []
>>> i.append('item')
>>> `i`
"['item']"
>>> repr(i)
"['item']"
基本上,repr函數(shù)和反引號用來獲取對象的可打印的表示形式。你可以通過定義類的__repr__方法來控制你的對象在被repr函數(shù)調(diào)用的時(shí)候返回的內(nèi)容。