• python中的list和generator


    # -*- coding:utf-8 -*-
    # author : Keekuun
    
    # 列表生成式,list
    l1 = [i for i in range(10)]
    # 或者
    l2 = list(range(10))
    print(l1, l2)
    # type(l) list
    # 打印:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    l3 = [x * x for x in range(1, 11) if x % 2 == 0]
    print(l3)
    
    # 生成器,generator:惰性,可迭代
    g = (i for i in range(10))
    print(g)
    # 打印:<generator object <genexpr> at 0x0000027EC76F5F10>
    for i in g:
        print(i)

    列表生成式

    可以使用两层循环,可以生成全排列:
    >>> [m + n for m in 'ABC' for n in 'XYZ']
    ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

    运用列表生成式,可以写出非常简洁的代码。例如,列出当前目录下的所有文件和目录名,可以通过一行代码实现:
    >>> import os 
    >>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
    ['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']


    for循环其实可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value:
    >>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
    >>> for k, v in d.items():
    ... print(k, '=', v)
    ...
    y = B
    x = A
    z = C
    因此,列表生成式也可以使用两个变量来生成list:
    >>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
    >>> [k + '=' + v for k, v in d.items()]
    ['y=B', 'x=A', 'z=C']
    最后把一个list中所有的字符串变成小写:
    >>> L = ['Hello', 'World', 'IBM', 'Apple']
    >>> [s.lower() for s in L]
    ['hello', 'world', 'ibm', 'apple']

    生成器

    1、’创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator。

    2、通过next()函数获得generator的下一个返回值

    3、不断调用next(g)实在是太变态了,当值都被调用完之后,会抛出StopIteration的错误:正确的方法是使用for循环,因为generator也是可迭代对象

    明月装饰了你的窗子,你装饰了他的梦。
  • 相关阅读:
    CF763C Timofey and Remoduling
    CF762E Radio Stations
    CF762D Maximum Path
    CF763B Timofey and Rectangles
    URAL1696 Salary for Robots
    uva10884 Persephone
    LA4273 Post Offices
    SCU3037 Painting the Balls
    poj3375 Network Connection
    Golang zip压缩文件读写操作
  • 原文地址:https://www.cnblogs.com/zkkysqs/p/9398620.html
Copyright © 2020-2023  润新知