zoukankan      html  css  js  c++  java
  • 我的Python之路:迭代和解析

    一、基本概念

    由于与函数工具(map和filter)有关,又与循环有关,在这我们在次进行学习。

    二、列表解析与map

    Python中的内置函数ord返回一个单字符的ASCII编码如:

    1 t=ord("s")
    2 print(t)

    结果为:

    115

    现在,假设我们希望搜集整个字符串的ASCII编码,也许最直接的方法就是使用for循环。

    1 res=[]
    2 for x in "fdsga":
    3   res.append(ord(x))
    4 print(res)

    结果为:

    [102, 100, 115, 103, 97]

    然而我们现在知道了map函数,我们能够使用一个单个函数调用,而不用关心代码中的列表结构,使实现更为简单

    1 res1=list(map(ord,'sadfadsf'))
    2 print(res1)
    3 res2=[ord(x)for   x in  "safdsg"]
    4 print(res2)

    结果为:

    [115, 97, 100, 102, 97, 100, 115, 102]
    [115, 97, 102, 100, 115, 103]

    所以在这我们可以看出列表解析是在一个序列值上应用一个任意表达式,将其结果收集到一个新的列表中返回。

    从语法上来说,列表解析是由方括号封装起来的。

    三、增加测试和嵌套循环

    就像我们刚刚看到都得map函数可以替代列表解析,为了测试表达式,这里的filter版本创建了一个小的lambda函数,为了对比也显示了for循环。

     1 res=[x for x in range(5) if x%2==0]
     2 print(res)
     3 res1=list(map((lambda x:x%2==0),range(5)))
     4 res2=list(filter((lambda x:x%2==0),range(5)))
     5 print(res1)
     6 print(res2)
     7 res3=[]
     8 for x in range(5):
     9     if x%2==0:
    10         res3.append(x)
    11 print(res3)

    其结果为:

    [0, 2, 4]
    [True, False, True, False, True]
    [0, 2, 4]
    [0, 2, 4]

    同时在这我们可以看到map与filter的用法,虽然;两者都有过滤的作用,但是其返回值却不相同

    当for分句嵌套在列表中时,它们工作起来就像等效的嵌套的for循环语句,比如如下代码:

    1 res=[x + y for x in [0,1,2] for y in [100,22,333]]
    2 print(res)
    3 res1=list((x1,y1) for x1 in range(5) if x1%2==0 for y1 in range(5) if y1 %2 ==1)
    4 print(res1)

    结果为:

    [100, 22, 333, 101, 23, 334, 102, 24, 335]
    [(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]

    这样运行起来就比较快。

  • 相关阅读:
    BEM(Block–Element-Modifier)
    http://element.eleme.io/#/zh-CN/component/quickstart
    Commit message 的写法规范。本文介绍Angular 规范(
    好的commit应该长啥样 https://github.com/torvalds/linux/pull/17#issuecomment-5654674
    代码管理
    if you have content fetched asynchronously on pages where SEO is important, SSR might be necessary
    Martin Fowler’s Active Record design pattern.
    The Zen of Python
    Introspection in Python How to spy on your Python objects Guide to Python introspection
    Object-Oriented Metrics: LCOM 内聚性的度量
  • 原文地址:https://www.cnblogs.com/alsely/p/6884351.html
Copyright © 2011-2022 走看看