Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1838896
  • 博文数量: 333
  • 博客积分: 10791
  • 博客等级: 上将
  • 技术积分: 4314
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-08 07:39
文章分类

全部博文(333)

文章存档

2015年(1)

2011年(116)

2010年(187)

2009年(25)

2008年(3)

2007年(1)

分类: Python/Ruby

2011-06-20 16:09:33

创建 & 分割字典 
如果你有两份 list 对象,希望通过这两个对象构建一个 dict 对象。 

Python代码   

1.  given = ['John''Eric''Terry''Michael']  

2.  family = ['Cleese''Idle''Gilliam''Palin']  

3.  pythons = dict(zip(given, family))  

4.  >>> pprint.pprint(pythons)  

5.  {'John''Cleese',  

6.   'Michael''Palin',  

7.   'Eric''Idle',  

8.   'Terry''Gilliam'}  


同样,如果希望获取两份列表,也是非常简单: 

Python代码   

1.  >>> pythons.keys()  

2.  ['John''Michael''Eric''Terry']  

3.  >>> pythons.values()  

4.  ['Cleese''Palin''Idle''Gilliam']  


需要注意的是,上面 list 虽然是有序的,但是 dict 中的  keys values 是无序的,这正是因为 dict 本质就是无序存储的。 


索引 & (1) 
如果你需要一个列表,这里有一个可爱的方式来节省你的输入: 

Python代码   

1.  >>> items = 'zero one two three'.split()  

2.  >>> print items  

3.  ['zero''one''two''three']  


如果我们需要遍历这个 list ,而且需要 index item 

Python代码   

1.                    - or -  

2.  i = 0  

3.  for item in items:      for i in range(len(items)):  

4.      print i, item               print i, items[i]  

5.      i += 1  



索引 & (2): enumerate 
通过 enumerate 可以返回 list 中的 (index, item)元组: 

Python代码   

1.  >>> print list(enumerate(items))  

2.  [(0'zero'), (1'one'), (2'two'), (3'three')]  


于是,遍历list获取index item 就更加简单了: 

Python代码   

1.  for (index, item) in enumerate(items):  

2.      print index, item  

 

Python代码   

1.  # compare:              # compare:  

2.  index = 0               for i in range(len(items)):  

3.  for item in items:              print i, items[i]  

4.      print index, item  

5.      index += 1  


不难看出,使用 enumerate 比起下面两种方式,更加简单,更加容易阅读,这正是我们想要的。 
下面是例子是如何通过 enumerate 返回迭代器: 

Python代码   

1.  >>> enumerate(items)  

2.  0x011EA1C0>  

3.  >>> e = enumerate(items)  

4.  >>> e.next()  

5.  (0'zero')  

6.  >>> e.next()  

7.  (1'one')  

8.  >>> e.next()  

9.  (2'two')  

10. >>> e.next()  

11. (3'three')  

12. >>> e.next()  

13. Traceback (most recent call last):  

14.   File "", line 1in ?  

15. StopIteration  




默认参数值 
这是对于一个初学者常犯的错误,甚至于一些高级开发人员也会遇到,因为他们并不了解 Python 中的 names. 

Python代码   

1.  def bad_append(new_item, a_list=[]):  

2.      a_list.append(new_item)  

3.      return a_list  


这里的问题是,a_list是一个空列表,默认值是在函数定义时进行初始化。因此,每次调用该函数,你会得到不相同的默认值。尝试了好几次: 

Python代码   

1.  >>> print bad_append('one')  

2.  ['one']  

3.  >>> print bad_append('two')  

4.  ['one''two']  


列表是可变对象,你可以改变它们的内容。正确的方式是先获得一个默认的列表(或dict,或sets)并在运行时创建它。 

Python代码   

1.  def good_append(new_item, a_list=None):  

2.      if a_list is None:  

3.          a_list = []  

4.      a_list.append(new_item)  

5.      return a_list  





判断 True  

Python代码   

1.  # do this:        # not this:  

2.  if x:             if x == True:  

3.      pass              pass  


它的优势在于效率和优雅。 
判断一个list 

Python代码   

1.  # do this:        # not this:  

2.  if items:         if len(items) != 0:  

3.      pass              pass  

4.    

5.                    # and definitely not this:  

6.                    if items != []:  

7.                        pass  




True  
TrueFalse是内置的bool类型的布尔值的实例。谁都只有其中的一个实例。 

False

True

False (== 0)

True (== 1)

"" (empty string)      

any string but "" (" ", "anything")

0, 0.0     

any number but 0 (1, 0.1, -1, 3.14)

[], (), {}, set()     

any non-empty container ([0], (None,), [''])

None     

almost any object that's not explicitly False



简单比复杂好 
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. 
     —Brian W. Kernighan 

不要重新发明轮子 
在写任何代码之前
 

·         .

·         检查Python的包索引 (the "Cheese Shop"):

           

·         Search the web. Google is your friend.

阅读(762) | 评论(0) | 转发(0) |
0

上一篇:python学习(续3)

下一篇:web上运行linux

给主人留下些什么吧!~~