码迷,mamicode.com
首页 > 编程语言 > 详细

第二天 Python3.4.2 里面的字典 列表解析等等

时间:2016-02-27 22:00:49      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:

一.字典

1.字典是一种无序集合

2.字典是一种KV结构

3.value可以是任何对象

4.key必须是可以hash对象

二.列表解析

1.列表解析是python重要的语法课

2.列表解析的速度比for in 迭代快

例子1:

In [1]: lst = list(range(10))

In [2]: lst
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

列表解析: In [
3]: [x+1 for x in lst] Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 

麻烦的写法:

In [4]: l = []

In [5]: for x in lst:
   ...:     l.append(x+1)
   ...:     

In [6]: l
Out[6]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

在执行效率上看:

(test_3.4.2) [root@Minion1 ~]# vim test_time.py    
import timeit

lst = range(10)

def fn1():
        [x+1 for x in lst]


def fn2():

        l = []
        for x in lst:
                l.append(x+1)

print (timeit.timeit([x+1 for x in range(10)]))

print (timeit.timeit(‘‘‘
l = []
for x in range(10):
        l.append(x+1)


‘‘‘))
其结果:

(test_3.4.2) [root@Minion1 ~]# python test_time.py
2.363238713995088
2.931454276003933

明显的列表解析需要的时间快一些。

 

 

 3.字典解析

ret = {exprk:exprv for item in iterator}

等价于:

  ret = dict {}

  for item in iterator:

    ret.update({exprk,exprv})

4.带条件的列表解析:

  

In [7]: lst
Out[7]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [8]: [x+1 for x in lst if x % 2 == 0]
Out[8]: [1, 3, 5, 7, 9]
相当于:
In [
12]: l=[] In [13]: for x in lst: ....: if x % 2 ==0: ....: l.append(x+1) ....: In [14]: print (l) [1, 3, 5, 7, 9]

 

 4.1 带多个条件的列表解析:

In [15]: [x+1 for x in lst if x % 2 == 0 if x >2]
Out[15]: [5, 7, 9]

In [16]: l = []

In [17]: for x in lst:
   ....:     if x % 2 ==0 and x >2:
   ....:         l.append(x+1)
   ....: print (l)
   ....: 
[5, 7, 9]  

4.1 笛卡尔积
ret = [expression for x in x for y in y]

技术分享
In [18]: l1=[1,3,5,7,9]

In [19]: l2=[0,2,4,6,8]

In [20]: [(x,y) for x in l1 for y in l2]
Out[20]: 
[(1, 0),
 (1, 2),
 (1, 4),
 (1, 6),
 (1, 8),
 (3, 0),
 (3, 2),
 (3, 4),
 (3, 6),
 (3, 8),
 (5, 0),
 (5, 2),
 (5, 4),
 (5, 6),
 (5, 8),
 (7, 0),
 (7, 2),
 (7, 4),
 (7, 6),
 (7, 8),
 (9, 0),
 (9, 2),
 (9, 4),
 (9, 6),
 (9, 8)]
View Code

 

 

第二天 Python3.4.2 里面的字典 列表解析等等

标签:

原文地址:http://www.cnblogs.com/tom-li/p/5223627.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!