zoukankan      html  css  js  c++  java
  • 列表推导式

    # 列表推导式不会再有变量泄露的问题
    '''
    列表推导式、生成器表达式,以及同他们相似的集合(set)推导和字典(dict)推导,在Python3 中都有了自己的局部作用域,就像函数
    表达式的内部的变量和赋值只在局部起作用,表达式的上下文里的同名变量还可以被正常引用,局部变量并不会影响到他们。
    '''
    
    # eg:python3 中:
    x = "ABC"
    dummy = [ord(x) for x in x]
    print(x)  # ABC
    print(dummy)  # [65, 66, 67]
    """
    在Python3中:
    x的值被保留了
    列表推导式也创建了正确的列表
    """
    
    # eg:python2 中:
    x = "my precious"
    dummy = [x for x in 'ABC']
    print(x)  # C
    
    colors = ["black", "white"]
    sizes = ['S', 'M', 'L']
    tshirts = [(color, size) for color in colors for size in sizes]
    print(tshirts)  # [('black', 'S'), ('black', 'M'), ('black', 'L'), ('white', 'S'), ('white', 'M'), ('white', 'L')]
    
    for color in colors:
        for size in sizes:
            print((color, size))  # 结果如下所示:
        """
        ('black', 'S')
        ('black', 'M')
        ('black', 'L')
        ('white', 'S')
        ('white', 'M')
        ('white', 'L')
        """
  • 相关阅读:
    codeforces 980A Links and Pearls
    zoj 3640 Help Me Escape
    sgu 495 Kids and Prizes
    poj 3071 Football
    hdu 3853 LOOPS
    hdu 4035 Maze
    hdu 4405 Aeroplane chess
    poj 2096 Collecting Bugs
    scu 4444 Travel
    zoj 3870 Team Formation
  • 原文地址:https://www.cnblogs.com/DJRemix/p/14170397.html
Copyright © 2011-2022 走看看