zoukankan      html  css  js  c++  java
  • python 列表解析

    列表解析函数式:
    [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'Pythonu6838u5fc3u7f16u7a0b', u'u5f53u5f53', 55.700000000000003, u'u6df1u5165Python', u'u65b0u534eu4e66u5e97']

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

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    java循环控制语句loop使用
    可实现的全局唯一有序ID生成策略
    ElasticSearch使用RestHighLevelClient进行搜索查询
    基于Redis实现分布式定时任务调度
    python脚本生成exe程序
    敏捷开发--工作流程的梳理
    React-菜鸟学习笔记(二)
    React-菜鸟学习笔记(一)
    ZooKeeper-基础介绍
    常用排序算法的Java实现与分析
  • 原文地址:https://www.cnblogs.com/wq242424/p/6646073.html
Copyright © 2011-2022 走看看