• 列表推导式.生成器表达式及部分内置函数


    一.列表推导式和生成器表达式

    l = [i for i in range(10)]
    print(l)
    l1 = ['选项%s'%i for i in range(10)]
    print(l1)

     

    1.把列表解析的[]换成()得到的就是生成器表达式

    2.列表解析与生成器表达式都是一种便利的编程方式,只不过生成器表达式更节省内存

    3.Python不但使用迭代器协议,让for循环变得更加通用。大部分内置函数,也是使用迭代器协议访问对象的。例如, sum函数是Python的内置函数,该函数使用迭代器协议访问对象,而生成器实现了迭代器协议,所以,我们可以直接这样计算一系列值的和:

    sum(x ** 2 for x in range(4))

    推导式套路

    之前我们已经学习了最简单的列表推导式和生成器表达式。但是除此之外,其实还有字典推导式、集合推导式等等。

    下面是一个以列表推导式为例的推导式详细格式,同样适用于其他推导式。

    variable = [out_exp_res for out_exp in input_list if out_exp == 2]
      out_exp_res:  # 列表生成元素表达式,可以是有返回值的函数。
      for out_exp in input_list:  # 迭代input_list将out_exp传入out_exp_res表达式中。
      if out_exp == 2:  # 根据条件过滤哪些值可以。

     

     

    列表推导式

    例一:30以内所有能被3整除的数

    multiples = [i for i in range(30) if i % 3 is 0]
    print(multiples)
    # Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

     

    例二:30以内所有能被3整除的数的平方

    def squared(x):
        return x*x
    multiples = [squared(i) for i in range(30) if i % 3 is 0]
    print(multiples)

     

    例三:找到嵌套列表中名字含有两个‘e’的所有名字

    names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
             ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
    
    print([name for lst in names for name in lst if name.count('e') >= 2])  # 注意遍历顺序,这是实现的关键

     

    字典推导式

    例一:将一个字典的key和value对调

    mcase = {'a': 10, 'b': 34}
    mcase_frequency = {mcase[k]: k for k in mcase}
    print(mcase_frequency)

     

    例二:合并大小写对应的value值,将k统一成小写

    mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
    mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys()}
    print(mcase_frequency)

     

    集合推导式

    例:计算列表中每个值的平方,自带去重功能

    squared = {x**2 for x in [1, -1, 2]}
    print(squared)
    # Output: set([1, 4])

     

    练习题:

    例1:  过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母

    例2:  求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表

    例3:  求M中3,6,9组成的列表M = [[1,2,3],[4,5,6],[7,8,9]]

    二.内置函数(上)

      我们一起来看看python里的内置函数。什么是内置函数?就是Python给你提供的,拿来直接用的函数,比如print,input等等。截止到python版本3.6.2,现在python一共为我们提供了68个内置函数。它们就是python提供给你直接可以拿来使用的所有函数。这些函数有些我们已经用过了,有些我们还没用到过,还有一些是被封印了,必须等我们学了新知识才能解开封印的。那今天我们就一起来认识一下python的内置函数。这么多函数,我们该从何学起呢?

     

    2.1作用域相关

    locals :函数会以字典的类型返回当前位置的全部局部变量。

    globals:函数以字典的类型返回全部全局变量。

    a = 1
    b = 2
    print(locals())
    print(globals())
    # 这两个一样,因为是在全局执行的。
    
    ##########################
    
    def func(argv):
        c = 2
        print(locals())
        print(globals())
    func(3)
    
    #这两个不一样,locals() {'argv': 3, 'c': 2}
    #globals() {'__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None, 
    '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000024409148978>,
    '__spec__': None, '__file__': 'D:/lnh.python/.../内置函数.py', 'func': <function func at 0x0000024408CF90D0>,
    '__name__': '__main__', '__package__': None}

    2.2其他相关

    2.2.1 字符串类型代码的执行 eval,exec,complie

      eval:执行字符串类型的代码,并返回最终结果。

    eval('2 + 2')  # 4
    n=81
    eval("n + 4")  # 85
    eval('print(666)')  # 666

      exec:执行字符串类型的代码。

    s = '''
    for i in [1,2,3]:
        print(i)
    '''
    exec(s)

      compile:将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值。

    '''
    参数说明:   
    
    1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。  
    
    2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。  
    
    3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;
    当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。
    ''' >>> #流程语句使用exec >>> code1 = 'for i in range(0,10): print (i)' >>> compile1 = compile(code1,'','exec') >>> exec (compile1) >>> #简单求值表达式用eval >>> code2 = '1 + 2 + 3 + 4' >>> compile2 = compile(code2,'','eval') >>> eval(compile2) >>> #交互语句用single >>> code3 = 'name = input("please input your name:")' >>> compile3 = compile(code3,'','single') >>> name #执行前name变量不存在 Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> name NameError: name 'name' is not defined >>> exec(compile3) #执行时显示交互命令,提示输入 please input your name:'pythoner' >>> name #执行后name变量有值 "'pythoner'"

    有返回值的字符串形式的代码用eval,没有返回值的字符串形式的代码用exec,一般不用compile。

    2.2.2 输入输出相关 input,print

      input:函数接受一个标准输入数据,返回为 string 类型。

      print:打印输出。

    ''' 源码分析
    def print(self, *args, sep=' ', end='
    ', file=None): # known special case of print
        """
        print(value, ..., sep=' ', end='
    ', file=sys.stdout, flush=False)
        file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件
        sep:   打印多个值之间的分隔符,默认为空格
        end:   每一次打印的结尾,默认为换行符
        flush: 立即把内容输出到流文件,不作缓存
        """
    '''
    
    print(111,222,333,sep='*')  # 111*222*333
    
    print(111,end='')
    print(222)  #两行的结果 111222
    
    f = open('log','w',encoding='utf-8')
    print('写入文件',file=f,flush=True)
    

    2.2.3内存相关 hash id

      hash:获取一个对象(可哈希对象:int,str,Bool,tuple)的哈希值。

    print(hash(12322))
    print(hash('123'))
    print(hash('arg'))
    print(hash('alex'))
    print(hash(True))
    print(hash(False))
    print(hash((1,2,3)))
    
    '''
    12322
    -2996001552409009098
    -4637515981888139739
    2311495795356652852
    1
    0
    2528502973977326415
    '''

    id:用于获取对象的内存地址。

    print(id(123))  # 1674055952
    print(id('abc'))  # 2033192957072

    2.2.3文件操作相关

      open:函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。

    2.2.4模块相关__import__ 

      __import__:函数用于动态加载类和函数 。

    2.2.5帮助

      help:函数用于查看函数或模块用途的详细说明。

    print(help(list))
    Help on class list in module builtins:
    
    class list(object)
     |  list() -> new empty list
     |  list(iterable) -> new list initialized from iterable's items
     |  
     |  Methods defined here:
     |  
     |  __add__(self, value, /)
     |      Return self+value.
     |  
     |  __contains__(self, key, /)
     |      Return key in self.
     |  
     |  __delitem__(self, key, /)
     |      Delete self[key].
     |  
     |  __eq__(self, value, /)
     |      Return self==value.
     |  
     |  __ge__(self, value, /)
     |      Return self>=value.
     |  
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |  
     |  __getitem__(...)
     |      x.__getitem__(y) <==> x[y]
     |  
     |  __gt__(self, value, /)
     |      Return self>value.
     |  
     |  __iadd__(self, value, /)
     |      Implement self+=value.
     |  
     |  __imul__(self, value, /)
     |      Implement self*=value.
     |  
     |  __init__(self, /, *args, **kwargs)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  __iter__(self, /)
     |      Implement iter(self).
     |  
     |  __le__(self, value, /)
     |      Return self<=value.
     |  
     |  __len__(self, /)
     |      Return len(self).
     |  
     |  __lt__(self, value, /)
     |      Return self<value.
     |  
     |  __mul__(self, value, /)
     |      Return self*value.n
     |  
     |  __ne__(self, value, /)
     |      Return self!=value.
     |  
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |  
     |  __repr__(self, /)
     |      Return repr(self).
     |  
     |  __reversed__(...)
     |      L.__reversed__() -- return a reverse iterator over the list
     |  
     |  __rmul__(self, value, /)
     |      Return self*value.
     |  
     |  __setitem__(self, key, value, /)
     |      Set self[key] to value.
     |  
     |  __sizeof__(...)
     |      L.__sizeof__() -- size of L in memory, in bytes
     |  
     |  append(...)
     |      L.append(object) -> None -- append object to end
     |  
     |  clear(...)
     |      L.clear() -> None -- remove all items from L
     |  
     |  copy(...)
     |      L.copy() -> list -- a shallow copy of L
     |  
     |  count(...)
     |      L.count(value) -> integer -- return number of occurrences of value
     |  
     |  extend(...)
     |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
     |  
     |  index(...)
     |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
     |      Raises ValueError if the value is not present.
     |  
     |  insert(...)
     |      L.insert(index, object) -- insert object before index
     |  
     |  pop(...)
     |      L.pop([index]) -> item -- remove and return item at index (default last).
     |      Raises IndexError if list is empty or index is out of range.
     |  
     |  remove(...)
     |      L.remove(value) -> None -- remove first occurrence of value.
     |      Raises ValueError if the value is not present.
     |  
     |  reverse(...)
     |      L.reverse() -- reverse *IN PLACE*
     |  
     |  sort(...)
     |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  __hash__ = None
    
    None
    
    Process finished with exit code 0

    2.2.6调用相关

      callable:函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。

    >>>callable(0)
    False
    >>> callable("runoob")
    False
     
    >>> def add(a, b):
    ...     return a + b
    ... 
    >>> callable(add)             # 函数返回 True
    True
    >>> class A:                  #
    ...     def method(self):
    ...             return 0
    ... 
    >>> callable(A)               # 类返回 True
    True
    >>> a = A()
    >>> callable(a)               # 没有实现 __call__, 返回 False
    False
    >>> class B:
    ...     def __call__(self):
    ...             return 0
    ... 
    >>> callable(B)
    True
    >>> b = B()
    >>> callable(b)               # 实现 __call__, 返回 True

    2.2.7查看内置属性

      dir:函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

    >>>dir()   #  获得当前模块的属性列表
    ['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
    >>> dir([ ])    # 查看列表的方法
    ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', 

    '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__',

    '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__',

    '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop',

    'remove', 'reverse', 'sort']
  • 相关阅读:
    android常用的Application类
    Android一些问题的解决方案
    MakeFile相关
    Android源码与设计模式之notifyDataSetChanged()方法与观察者模式
    Activity启动模式与onNewIntent()简述
    (转)eval与迭代
    ADB命令
    其他常用工具类
    文件操作常用工具方法
    [TJOI2007] 可爱的质数
  • 原文地址:https://www.cnblogs.com/caisong/p/9204361.html
Copyright © 2020-2023  润新知