python 语法笔记

来源:互联网 发布:客户生日提醒软件 编辑:程序博客网 时间:2024/05/29 07:12
[python] view plaincopy
  1. i=int(raw_input("i= "))  
  2. if i==0 
  3.    print 'i=0'  
  4. elif i==1 
  5.    print 'i=1'  
  6. else 
  7.    print 'wrong input'  

 

注意这里的冒号

注意这里的强制转换int(),否则raw_input输入的是字符串类型。不能比较。


 

[python] view plaincopy
  1. i=0  
  2. total=0  
  3. while i<</span>10 
  4.     i+=1  
  5.     total=total+i  
  6.       
  7. print 'i is:',i,'total is:'total  

 


结果是55

注意没有++和=+

 

[python] view plaincopy
  1. total=0  
  2. for in range(0,11):  
  3.     total=total+i  
  4.   
  5. print total  

结果是55.

 

注意range的最后一个元素不算的。0+1+2+3+4+5+6+7+8+9+10


while和for中都可以使用 break和continue


函数:

 

[python] view plaincopy
  1. def printMax(a, b):  
  2.  if b:  
  3.    print a, 'is maximum\n'  
  4.  else 
  5.    print b, 'is maximum\n'  
[python] view plaincopy
  1. printMax( 34 
  2. 5  
  3. 7  
  4. printMax(x, y)  

注意def后面也有冒号

 


函数的默认参数:

 

[python] view plaincopy
  1. def say(message, times 1):  
  2.     print message times  
  3. say( 'Hello'  
  4. say( 'World' 5 

结果显示

 

>>> 
Hello
WorldWorldWorldWorldWorld


文档字符串,它通常被简称为 docstrings 。DocStrings是一个重要的工具,由于它帮助你的程序文档更加简单易懂。

你可以使用__doc__(注意双下划线)调用printMax函数的文档字符串属性。

或者help(printMax)。记住按q退出help

[python] view plaincopy
  1. def printMax(x, y):  
  2. '''Prints the maximum of two numbers.

      
[python] view plaincopy
  1. The two values must be integers.'' 
  2. if y:  
  3.   print x, 'is maximum'  
  4. else 
  5.   print y, 'is maximum'  
[python] view plaincopy
  1. printMax( 35 
  2. print printMax.__doc__  

显示

 

>>> 
5 is maximum
Prints the maximum of two numbers.
 The two values must be integers.


模块的__name__
每个Python模块都有它的__name__,如果它是'__main__',这说明这个模块被用户单独运行,我们可以进行相应的恰当操作。

比如一个模块test.py

if __name__ == '__main__' :
    print 'This program is beingrun by itself'
else:
    print 'I am being importedfrom another module'

如果单独运行test.py,会显示

>>> 
This program is being run by itself

如果在别的程序里面import test

会显示

>>> import test
I am being imported from another module


列表

 

[python] view plaincopy
  1. shoplist=['A','C','B','D' 
[python] view plaincopy
  1. print shoplist[0:4 
  2. print 'I have',len(shoplist),'items to purchase.'  
  3. print 'These items are:'                                    Notice the comma at end of the line  
  4. for item in shoplist:  
  5.  print item,  
  6. print '\nI also have to buy E.'  
  7. shoplist.append('E' 
  8. print 'My shopping list is now',shoplist  
  9. print 'I will sort my list now'  
  10. shoplist.sort()  
  11. print 'Sorted shopping list is',shoplist  
  12. print 'The first item will buy is',shoplist[0 
  13. olditem=shoplist[0 
  14. del shoplist[0 
  15. print 'I bought the',olditem  
  16. print 'My shopping list is now',shoplist  

 


结果显示
>>> 

['A', 'C', 'B', 'D']
I have 4 items to purchase.
These items are: A C B D 
I also have to buy E.
My shopping list is now ['A', 'C', 'B', 'D', 'E']
I will sort my list now
Sorted shopping list is ['A', 'B', 'C', 'D', 'E']
The first item I will buy is A
I bought the A
My shopping list is now ['B', 'C', 'D', 'E']


shoplist[0:4] 返回从位置0开始,包括位置1,2,3,但是停止在位置4的一个序列切片.


 

元组:元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变


 

 

[python] view plaincopy
  1. zoo=('A','B','C' 
  2. print 'Number of animals in the zoo is',len(zoo)  
  3. new_zoo=('D','E',zoo)  
  4. print 'Number of animals in the new zoo is',len(new_zoo)  
  5. print 'All animals in new zoo are',new_zoo  
  6. print 'Animals brought from old zoo are',new_zoo[2 
  7. 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 ('D', 'E', ('A', 'B', 'C'))
Animals brought from old zoo are ('A', 'B', 'C')
Last animal brought from old zoo is C


Perl程序员的注释列表之中的列表不会失去它的身份,即列表不会像Perl中那样被打散。同样元组中的元组,或列表中的元组,或元组中的列表等等都是如此。只要是Python,它们就只是使用另一个对象存储的对象


字典:

 

[python] view plaincopy
  1. ab={ 'A' 'a@intel.com' 
  2.      'B' 'b@intel.com' 
  3.      'C' 'c@intel.com' 
  4.      'D' 'd@intel.com'  
  5.   
  6. print "A's address is %s" �['A']  
  7. Adding key/value pair  
  8. ab['E']='e@intel.com'  
  9. Deleting key/value pair  
  10. del ab['D' 
  11. print 'There are %d contacts in the address-book' %len(ab)  
  12. for name,address in ab.items():  
  13.  print 'Contact %s at %s' %(name,address)  
  14. if 'E' in ab:                   OR ab.has_key('Guido')  
  15.  print "E's address is %s" �['E']  

结果显示

 

>>> 
A's address is a@intel.com
There are 4 contacts in the address-book
Contact A at a@intel.com
Contact C at c@intel.com
Contact B at b@intel.com
Contact E at e@intel.com
E's address is e@intel.com


我们使用字典的items方法,来使用字典中的每个键/值对。这会返回一个元组的列表,其中每个元组都包含一对项目——键与对应的值。


参考,赋值:

只是如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单对象),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都是参考同一个对象

[python] view plaincopy
  1. shoplist=['A','B','C','D' 
  2.   
  3. print 'Simple Assignment'  
  4. mylist=shoplist   
  5. del shoplist[0 
  6. print 'shoplist is',shoplist  
  7. print 'mylist is',mylist  
  8.   
  9. print 'Copy by making full slice'  
  10. mylist=shoplist[:]   
  11. del mylist[0  
  12. print 'shoplist is'shoplist  
  13. print 'mylist is'mylist  

显示结果一目了然:

 

>>> 
Simple Assignment
shoplist is ['B', 'C', 'D']
mylist is ['B', 'C', 'D']
Copy by making a full slice
shoplist is ['B', 'C', 'D']
mylist is ['C', 'D']


字符串

 

[python] view plaincopy
  1. name='Swaroop'   
  2. if name.startswith('Swa'):  
  3.  print 'Yes, the string starts with "Swa"'  
  4. if 'a' in name:  
  5.  print 'Yes, it contains the string "a"'  
  6. if name.find('war')!=-1 
  7.  print 'Yes, it contains the string "war"'  
  8.   
  9. A='  
  10. mylist=['Brazil','Russia','India','China' 
  11. print A.join(mylist)  


 

结果显示

>>> 
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil * Russia * India * China



dictionary
d={'server': 'mpilgrim', 'uid': 'sa', 'datab ase': 'master','retrycount': 3}
del d['server']
>>> d .keys()
>>> d .values() 
>>> d .items()

L i s t  
 list = ["a", "b", "mpilgrim", "z","example"] 

list 的 slice
>>> list[:3] 
['a', 'b', 'mpilgrim']
        list.append("new")    就是 ["a","b", "mpilgrim", "z", "example","new"] 
或者  list.insert(2, "new")   

extend函数用来连接两个list
list2=["x" , "y"]
 list.extend(list2)    就是 ["a", "b", "mpilgrim", "z","example","x" , "y"] 
注意区别extend 和append   list.append(list2)   就是 ["a", "b","mpilgrim", "z", "example",["x" , "y"]] 
Lists 也可以用 + 运算符连接起来。list = list + otherlist 相当于
list.extend(otherlist)。

列表索引
 list.index("example") 
>>>5

从  l i s t   中删除元素  (remove 从 list 中删除一个值的首次出现。)
 list.remove("z") 

 li.pop( ) 删除 list 的最后一个元素,然后 返回删除元素的值.

元组
t =("a", "b", "mpilgrim", "z", "example")
>>> t[0]                            
'a'

T u p l e   没有append, remove,index等方法,然而,您可以使用 in 来查看一个元素是否存在于 tuple 中。

 一次赋 多值
>>> v =('a', 'b',  'e')
>>> (x, y, z) = v   (1)
>>> x
'a'
>>> y
'b'
>>> z
'e'

格式化显示
usercount = 6
print  "user count is %d" % usercount


















def buildConnectionString(params):
  """Build aconnection string from adictionary of par ameters.
  Returns string."""
  return ";".join(["%s=%s" % (k, v) for k, vin params.items()])


myParams = {"se rver":"mpilgrim", \
    "database":"master",\
    "uid":"sa", \
    "pwd":"secret" \
   }

print buildConnectionString(myParams)

>>> 
pwd=secret;uid=sa;se rver=mpilgrim;database=master




>>> li = ['se rver=mpilgrim', 'uid=sa','database=master', 'pwd=secret']
>>> s = ";".join(li)
>>> s
'server=mpilgrim;uid=sa;database=master;pwd=secret'
>>> s.split(";")  
['server=mpilgrim', 'uid=sa', 'datab ase=master','pwd=secret']



List 解析介绍
>>> li = [1, 9, 8, 4]
>>> list2= [elem*2 for elem inli] 
>>> list2
[2, 18, 16, 8]
对 list 的解析并不改变原始的 list,只是返回一个新List

>>> params = {"server":"mpilgrim","database":"master", "uid":"sa", "pwd":"secret"}
>>> params.items()
[('server', 'mpilgrim'), ('uid', 'sa'), ('database','master'), ('pwd', 'secret')]
>>> [k for k, v in params.items()]             (1)
['server', 'uid', 'database', 'pwd']
>>> [v for k, v in params.items()]             (2)
['mpilgrim', 'sa', 'master', 'secret']
>>> ["%s=%s" % (k, v) for k, v in params.items()](3)
['server=mpilgrim', 'uid=sa', 'database=master','pwd=secret']
>>>s= ";".join(["%s=%s" % (k, v) for k, v inparams.items()])
>>> s
'server=mpilgrim;uid=sa;database=master;pwd=secret'
join 只能用于元素是字符串的 list;它不进行任何的强制类型转换。
>>>s.split(";")
['server=mpilgrim', 'uid=sa','database=master', 'pwd=secret']

split还可以带参数,
anystring.split(delimiter, 1)是一个有用的技术,在您想要搜索一个子串,然后分别
处理字符前半部分 (即 list 中第一个元素) 和后半部分 (即list 中第二个元素) 
时,使用这个技术。

def info(object, spacing=10,collapse=1): 
   。。。。。。
  。。。。。
 。。。。。

调用时可以直接
info(Object1)
,也可以info(Object1,11)
或者info(Object1,15, 3)
更可以 info(collapse=5, object=Object1, spacing=12)  这里顺序甚至都无关紧要,只要指定参数名即可。


内置函数type ,再引入types很有用。
import types

li=[]
print type(li)
a=1
if type(a)==types.IntType:
    print "yes"

>>> 
yes


内置函数str, 将参数强制转换为字符串。
>>> str(1)
'1'
>>> horsemen = ['war', 'pestilence', 'famine']
>>> str(horsemen )
"['war', 'pestilence', 'famine', 'Powerbuilder']"

内置函数dir,可以返回任意对象的属性和方法列表
>>> li = []
>>> dir(li)        
['append', 'count', 'extend', 'index', 'insert','pop','remove', 'reverse', 'sort']
>>> d = {}
>>> dir(d)         
['clear', 'copy', 'get', 'has_key', 'items', 'keys','setdefault', 'update', 'values']



通过 getattr 获取对象引用
>>> li = ["Larry", "Curly"]
>>> li.pop                   
注意这里不是使用的li.pop()
而是只返回了pop这个方法的引用。

通常,getattr(object, "attribute") 等价于 object.attribute

>>> getattr(li,"append")("Moe") 
就相当于li.append("Moe").
现在li就是["Larry", "Curly", "Moe"]

getattr 不仅仅适用于内置数据类型,也可作用于模块。

getattr常见的使用模式是作为一个分发者。举个例子,如果你有一个程序可以以不同的格式输出数据,你可以为每种输出格式定义各自的格式输出函数,然后使用唯一的分发函数调用所需的格式输出函数。

例如,让我们假设有一个以 HTML、XML 和普通文本格式打印站点统计的程序。
输出格式在命令行中指定,或者保存在配置文件中。statsout 模块定义了三个
函数:output_html、output_xml 和 output_text。然后主程序定义了唯一的输出函数,

import statsout
def output(data, format="text"):                      
    output_function =getattr(statsout, "output_%s" % format) 
    returnoutput_function(data)                  

值得庆幸的是,getattr 能够使用可选的第三个参数,一个缺省返回值
 output_function = getattr(statsout,"output_%s" % format, statsout.output_text)       
如果第二个参数指定的属性或者方法没能找到,则将返回这个缺省返回值

列表过滤:
>>> li = ["a", "mpilgrim", "f oo", "b", "c", "b", "d", "d"]
>>> [elem for elem in li iflen(elem)> 1]     
['mpilgrim', 'foo']


  and   和 or   的特殊性质
使用 and 时,在布尔环境中从左到右演算表达式的值。如果布尔环境中的所有值都为真,那么 and 返回最后
一个值。如果布尔环境中的某个值为假,则返回第一个假值。
 0、''、[]、()、{}、None在布尔环境中为假;其它任何东西都为真。
>>> 'a' and 'b'       
'b'
>>> 1 and 2 and 3
3
>>> 'a' and {} and 'b'
{}

or 和and正好相反。在布尔环境中从左到右演算表达式的值。如果布尔环境中的所有值都为假,那么or返回最后一个值。如果布尔环境中的某个值为真,则返回第一个真值。
>>> 'a' or 'b'
'a'
>>> 0 or {} or []
[]

下面介绍一个跟C语言中 bool? a :b 同样功能的东西
bool and a or b
如果bool是真,则返回a,否则返回b

>>> a=''
>>> b="second"
>>> 1 and [a] or [b]
['']
这里把a放在[ ]中是确保表达式不是假。如果你确定a一定不是假,也可以用1 and a or b 。
这个技巧在lambda函数中这种不允许使用if 的语句时很有用。

那我们就看看lambda函数是个啥吧:
一般函数。
>>> def f(x) :
...    return x*2
... 
>>> f(3)
6
lambda  的函数允许你快速定义单行的最小函数
>>> g = lambda x: x*2  
>>> g(3)
6
>>> (lambda x: x*2 )(3)  
6

一般我将它们用在需要封装特殊的、非重用代码上,避免令我的代码充斥着大量单行函数。
比如
processFunc = collapse and (lambdas: " ". join(s.split())) or(lambda s: s)

注意这里使用了 and-or 技巧的简单形式,它是没问题的,因为 lambda 函数在布尔环境中总是为真。
 不带参数的 split 按照空白进行分割。
processFunc 现在是一个函数,但是它到底是哪一个函数还要取决于 collapse 变量。如果 collapse为真,processFunc(string) 将压缩空白;否则 processFunc(string)将返回未改变的参数。



[f for f in os.listdir("D:/1/") ifos.path.isfile(os.path.join("D:/1/",f))]

过滤 列表。

注意这里的if后置 只能用于过滤列表。没有以下用法:
print "a" if 1


>>> info={'A':0,'B':1,'C':2}
>>> info.update({'D':3,'E':4})
>>> info
{'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3}



将浮点数转换为十六进制数据。
>>> struct.pack(">f", 1.5).encode('hex')
'3fc00000'

>表示big endian  <表示little endian f表示浮点数。



Python中,也有几个定义好的全局函数方便使用的,他们就是filter, map, reduce。
>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>>
>>> print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]
>>>
>>> print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>>
>>> print reduce(lambda x, y: x + y, foo)
139

什么时候使用lambda,什么时候不用,需要具体情况具体分析,只要表达的意图清晰就好。一般情况下,如果for..in..if能做的,我都不会选择lambda。
 比如上面filter的例子可以写成:  
print [x for x in foo if x % 3 == 0]

比如上面map的例子,可以写成:
print [x * 2 + 10 for x in foo]

     接下来分别介绍filter,map和reduce。

1、filter(bool_func,seq):此函数的功能相当于过滤器。调用一个布尔函数bool_func来迭代遍历每个seq中的元素;返回一个使bool_seq返回值为true的元素的序列。

    例如:

     

[python] viewplaincopy
  1. >>> filter(lambda x%2 == 0,[1,2,3,4,5])  
  2. [24 

   

2、map(func,seq1[,seq2...]):将函数func作用于给定序列的每个元素,并用一个列表来提供返回值;如果func为None,func表现为身份函数,返回一个含有每个序列中元素集合的n个元组的列表。

    例如:

    

[c-sharp] viewplaincopy
  1. >>> map(lambda None,[1,2,3,4])  
  2. [None, None, None, None]  
  3. >>> map(lambda 2,[1,2,3,4])  
  4. [2, 4, 6, 8]  
  5. >>> map(lambda 2,[1,2,3,4,[5,6,7]])  
  6. [2, 4, 6, 8, [5, 6, 7, 5, 6, 7]]  
  7. >>> map(lambda None,[1,2,3,4])  
  8. [None, None, None, None]  

   map(lambdax,y:x+y,[1,3,5],[2,4,6])

结果是[3,7,11]



如果碰到这样的两组序列:a =[1,2,3], b = [4,5],这里顺带比较一些map和zip

   map(None,a,b) 结果为[(1,4),(2,5),(3,None)]

   zip(a,b)      结果为 [(1,4),(2,5)]

上面的处理,可以看到map是做最大的集合,而zip则是根据最小的集合。


3、reduce(func,seq[,init]):func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值:如果初始值init给定,第一个比较会是init和第一个序列元素而不是序列的头两个元素。

    例如:

    

[c-sharp] viewplaincopy
  1. >>> reduce(lambda x,y y,[1,2,3,4])  
  2. 10  
  3. >>> reduce(lambda x,y y,[1,2,3,4],10)  
  4. 20  

    def myadd(x,y):  

    return x+y  

  sum=reduce(myadd,(1,2,3,4,5,6,7))

      printsum


0 0