• 生成器面试题之一


    阅读下面的代码,写出A0,A1,至An的最终值

    A0 = dict(zip(('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, 5)))
    A1 = range(10)
    A2 = [i for i in A1 if i in A0]
    A3 = [A0[s] for s in A0]
    A4 = [i for i in A1 if i in A3]
    A5 = {i:i*i for i in A1}
    A6 = [[i, i*i for i in A1]
    
    

    解答

    zip接收两个可迭代对象,返回一个zip对象,这个zip对象可以用next()取值,取出的值是一个个元组,python中关于zip的定义如下:

    class zip(object):
        """
        zip(iter1 [,iter2 [...]]) --> zip object
        
        Return a zip object whose .__next__() method returns a tuple where
        the i-th element comes from the i-th iterable argument.  The .__next__()
        method continues until the shortest iterable in the argument sequence
        is exhausted and then it raises StopIteration.
        """
    

    zip的使用方法 ```python obj = zip(('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, 5)) print(obj, type(obj)) #

    try:
    for i in range(10):
    print(next(obj))
    except StopIteration:
    print("结束了~")

    由上面的演示可以很容易得出
    ```python
    A0 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }
    
    

    A1就是生成器的简单测试,结果为

    A1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    

    A2为一个列表推导式,元素为满足以下两个条件的值: - i在A1中 - i在A0中 注意A0是一个字典,i在A0中等价于i在A0的键组成的列表(A0.keys())里,而A0的键都是字母,所以没有满足条件的i ```python A2 = []
    <br>
    s为A0的键,A0[s]为A0的值,因此结果是A0值组成的列表
    ```python
    A3 = [1, 2, 3, 4, 5]
    
    

    ```python A4 = [1, 2, 3, 4, 5]
    
    <br>
    ```python
    A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
    
    

    ```python A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36],[7, 49],[8, 64] [9, 81]]
  • 相关阅读:
    python基本数据类型及其使用方法
    爬虫基础
    HTML标签marquee实现滚动效果
    Python学习之路_day_32(基于tcp协议的套接字/粘包问题)
    Python学习之路_day_31(tcp协议/socket)
    Python学习之路_day_30(单例模式,网络编程)
    Python学习之路_day_29(异常处理,元类)
    Python学习之路_day_25(面向对象之封装/多态/组合)
    Python学习之路_day_24(面向对象之继承)
    Python学习之路_day_23(面向对象)
  • 原文地址:https://www.cnblogs.com/zzliu/p/10645371.html
Copyright © 2020-2023  润新知