代码改变世界

python 列表解析

2017-03-30 14:29  丨o聽乄雨o丨  阅读(331)  评论(0编辑  收藏  举报
列表解析函数式:
[expr for iter_var in iterable] [expr for iter_var in iterable if cond_expr]

exp:
1.
>>> seq = [11,10,9,9,5,35,8,20,31,72,54,53]
>>> [x for x in seq if x%2]
[11, 9, 9, 5, 35, 31, 53]
2.
>>> [(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)]

>>> [(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)]
3.经典例子
>>> 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"新华书店"},
      ]
# 列表中价格最低的书目
#原始方法:
>>> price=[] >>> for item in books: for p in item: if p == 'price': price.append(item[p]) >>> min(price) 23.699999999999999
#列表解析:
>>> 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']

此博客转载自:http://www.cnblogs.com/BeginMan/p/3164937.html