• 第17条:在参数上面迭代时,要多加小心


    实验中用的 init.py

    15
    35
    80
    

    def read_visits(data_path):
        with open(data_path) as f:
            for line in f:
                yield int(line)
    
    def normalize_copy(numbers):
        numbers = list(numbers)
        total = sum(numbers)
        result = []
        for value in numbers:
            percent = 100 * value / total
            result.append(percent)
        return result
    
    it = read_visits('__init__.py')
    percentages = normalize_copy(it)
    print(percentages)
    
    输出: 
    [11.538461538461538,26.923076923076923,61.53846153846154]
    
    

    2.传入函数

    def normalize_func(get_iter):
        total = sum(get_iter())
        result = []
        for value in get_iter():#New iterator
            percent = 100 * value / total
            result.append(percent)
        return result
    rcentages = normalize_func(lambda: read_visits('__init__.py'))
    print(percentages)
    

    2. 类的迭代器

    class ReadVisits(object):
        def __init__(self,data_path):
            self.data_path = data_path
    
        def __iter__(self):
            with open(self.data_path) as f:
                for line in f:
                    yield int(line)
    visits = ReadVisits('__init__.py')
    percentages = list(visits)
    print(percentages)
    输出:
    [15, 35, 80]
    

    3.限定必须传入容器对象

    def normalize_defensive(numbers):  
        if iter(numbers) is iter(numbers):  # An iterator -- bad!
            raise TypeError('Must supply a container')
        total = sum(numbers)
        result = []
        for value in numbers:
            percent = 100 * value / total
            result.append(percent)
        return result
    
    visits = [15,35,80]
    normalize_defensive(visits)
    visits = ReadVisits('__init__.py')
    a = normalize_defensive(visits)
    print('a',a)
    输出:a [11.538461538461538, 26.923076923076923, 61.53846153846154]
    
    • 把_iter._方法实现为生成器,即可定义自己的容器类型。
    • 想判断某个值是迭代器还是容器,可以拿该值为参数,两次调用iter函数,若结果相同,则是迭代器,调用内置的next函数,即可令该迭代器前进一步。
    写入自己的博客中才能记得长久
  • 相关阅读:
    Good Substrings CodeForces
    Watto and Mechanism Codeforces Round #291 (Div. 2)
    Codeforces Round #487 (Div. 2) A Mist of Florescence (暴力构造)
    Oulipo HDU
    POJ
    求值2 组合数公式题目
    URAL
    SCU
    【转】phpcms授课学习
    WordPress文章浏览历史插件
  • 原文地址:https://www.cnblogs.com/heris/p/14738535.html
Copyright © 2020-2023  润新知