zoukankan      html  css  js  c++  java
  • 第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函数,即可令该迭代器前进一步。
    写入自己的博客中才能记得长久
  • 相关阅读:
    2017.3.11[bzoj2440][中山市选2011]完全平方数
    2017.3.6[hihocoder#1415]后缀数组三·重复旋律3
    2017.3.4[hihocoder#1407]后缀数组二·重复旋律2
    [NOI2013]快餐店
    [HNOI2014]米特运输
    [HNOI2015]亚瑟王
    [JLOI2013]卡牌游戏
    [SDOI2010]地精部落
    [ZJOI2007]棋盘制作
    [AHOI2009]中国象棋
  • 原文地址:https://www.cnblogs.com/heris/p/14738535.html
Copyright © 2011-2022 走看看