python diary(part 1)

1 . negative index
>>>[1,2,3][-1]
3
>>>[1,2,3][-3]
1
>>>[1,2,3][-4]
index error

3 . range
>>>range(3)
[0,1,2]

4 . for each
>>>for i in range(3)
... print i
...
0
1
2
>>>[(i+1) for i in range(3)]
[1,2,3]

 

5 . writeline
>>>print i #this variable is out of for statement's range
2

6 . lambda expression
>>>map((lambda x:x+1),range(3))
[1,2,3]

7 . build-in function "map"
#grammar map(function,[])

8 . build-in function "sum"
#grammar sum([])
>>>sum([i for i in range(3)])
3
>>>sum(i for i in range(3))
3
#"i for i in range(3)" have returned an array,
#but when it is used as a statement ,there might be ambiguity

9 . append
>>>a=range(3)
>>>a.append(1) # append return None
>>>a
[0,1,2,1]

10 . None
>>>None
>>>print None
None

11 . build-in function "len"
>>>len(range(3))
3

12 . tuple
>>>1,2,3
(1,2,3)
>>>(1,2,3)[1]
2
>>>a,b,c=range(3) #tuple assignment
>>>a,b,c
(0,1,2)
>>>sum((a,b,c))
3
>>>sum(a,b,c)
typeerror: sum() takes at most 2 arguments (3 given)

13 . index range
>>>range(3)[0:2]
[0,1]
>>>range(3)[-2:2]
[1]
>>>range(3)[-2:1]
[]
>>>range(3)[-2:-1]
[1]
>>>range(3)[-2]
1

14 . build-in type string
>>>"1"
'1'
>>>'1'
'1'
>>>'1 2'.split() #as split(whitespace),include ' ' '\t' etc
['1','2']

15 . dictionary
>>>foo={'a':'A','b':'B'}
>>>foo
{'a':'A','b':'B'}
>>>foo={a:'A',b:'B'}#a is not treated as literal,a and b is assigned before
foo
{0:'A',1:'B'}

 16 . build-in function dict
 >>>foo=dict(a='a',b='b',c='c') #this grammar is difficult to understand
 >>>foo
 {'a':'a','b':'b','c':'c'}

17 . complex for statement
>>>[i*j for j in range(3) for i in range(4)] #sorted array return
[0,0,0,0,0,1,2,3,0,2,4,6]
>>>[[i*j for j in range(3)] for i in range(4)]
[[0,0,0],[0,0,1],[0,2,4],[0,3,6]]
>>>[[(i,j) for j in range(3)] for i in range(4)]
[[0,0,0],[0,0,1],[0,2,4],[0,3,6]]
>>>......

18 . build-in function zip
>>>zip(range(3),range(3))
[(0,0),(1,1),(2,2)]
>>>zip(range(3),range(2))
[(0,0),(1,1)]

19 . fromkeys
#waiting for filling

20 . default arguments
>>>def func(a='a',b='b'):
... print a+b
...
>>>func()
ab
>>>func(1,2)
3

posted @ 2008-02-25 10:51 nfa2dfa 阅读(68) 评论(0)  编辑 收藏 所属分类: python

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      


相关链接: