Python入门笔记(13):列表解析

时间:2023-11-25 18:36:32

一、列表解析

列表解析来自函数式编程语言(haskell),语法如下:

[expr for iter_var in iterable]
[expr for iter_var in iterable if cond_expr]

第一种语法:首先迭代iterable里所有内容,每一次迭代,都把iterable里相应内容放到iter_var中,再在表达式中应用该iter_var的内容,最后用表达式的计算值生成一个列表。

第二种语法:加入了判断语句,只有满足条件的内容才把iterable里相应内容放到iter_var中,再在表达式中应用该iter_var的内容,最后用表达式的计算值生成一个列表。

例子如下:

>>> seq = [11,10,9,9,5,35,8,20,31,72,54,53]
>>> filter(lambda x:x%2,seq)
[11, 9, 9, 5, 35, 31, 53]
>>> [x for x in seq if x%2]
[11, 9, 9, 5, 35, 31, 53]

更复杂的如求矩阵:

#3行5列的矩阵
>>> [(x+1,y+1) for x in range(3) for y in range(5)]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)]
#简单的3行3列
>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
#模拟
>>> for x in range(3):
    for y in range(3):
        print x,y

0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1

计算一个文件的字数和大小:

>>> import os
>>> f = open('demo.txt','r')
>>> #计算单词的个数
>>> len([word for line in f for word in line.split()])
1942
>>> #计算文件大小
>>> os.stat('demo.txt').st_size
14051L
>>> f.seek(0)  #seek()函数回到文件头部,因为迭代器已经访问完了文件的所有行
>>> sum([len(word) for line in f for word in line.split()])
10806
>>> f.close()
>>> 

经典例子:

books=[
        {"name":u"C#从入门到精通","price":23.7,"store":u"卓越"},
        {"name":u"ASP.NET高级编程","price":44.5,"store":u"卓越"},
        {"name":u"Python核心编程","price":24.7,"store":u"当当"},
        {"name":u"JavaScript大全","price":45.7,"store":u"当当"},
        {"name":u"Django简明教程","price":26.7,"store":u"新华书店"},
        {"name":u"深入Python","price":55.7,"store":u"新华书店"},
      ]

1、书籍信息中价格最低的

#No1:原始方式:
>>> price=[]
>>> for item in books:
    for p in item:
        if p == 'price':
            price.append(item[p])

>>> min(price)
23.699999999999999
#No2:列表解析:
>>> min([item[p] for item in books for p in item if p=='price'])
23.699999999999999
#Python相关书籍检索
for item in books:
    for p in item:
        if item['name'].find('Python')>=0:
            print item[p],  #24.7 Python核心编程 当当 55.7 深入Python 新华书店

total = [item[p] for item in books for p in item if item['name'].find('Python')>=0]
print total #[24.699999999999999, u'Python\u6838\u5fc3\u7f16\u7a0b', u'\u5f53\u5f53', 55.700000000000003, u'\u6df1\u5165Python', u'\u65b0\u534e\u4e66\u5e97']

二、生成器表达式

1、为什么要用到它?

2、它与列表解析的区别?