zoukankan      html  css  js  c++  java
  • pyextend库-merge可迭代对象合并函数

    pyextend - python extend lib

    merge (iterable1, *args)

    参数: 

    iterable1: 实现 __iter__的可迭代对象, 如 str, tuple, dict, list

    *args: 其他实现 __iter__的可迭代对象

    返回值:

    合并后的迭代对象

    使用范例:

        Example 1:
            source = ['a', 'b', 'c']
            result = merge(source, [1, 2, 3])
            self.assertEqual(result, ['a', 'b', 'c', 1, 2, 3])
    
            result = merge(source, [1, 2, 3], ['x', 'y', 'z'])
            self.assertEqual(result, ['a', 'b', 'c', 1, 2, 3, 'x', 'y', 'z'])
    
        Example 2:
            source = 'abc'
            result = merge(source, '123')
            self.assertEqual(result, 'abc123')
    
            result = merge(source, '123', 'xyz')
            self.assertEqual(result, 'abc123xyz')
    
        Example 3:
            source = ('a', 'b', 'c')
            result = merge(source, (1, 2, 3))
            self.assertEqual(result, ('a', 'b', 'c', 1, 2, 3))
    
            result = merge(source, (1, 2, 3), ('x', 'y', 'z'))
            self.assertEqual(result, ('a', 'b', 'c', 1, 2, 3, 'x', 'y', 'z'))
    
        Example 4:
            source = {'a': 1, 'b': 2, 'c': 3}
            result = merge(source, {'x': 'm', 'y': 'n'}, {'z': '1'})
            self.assertEqual(result, {'a': 1, 'b': 2, 'c': 3, 'x': 'm', 'y': 'n', 'z': '1'})

    代码:

    @accepts(iterable1='__iter__')
    def merge(iterable1, *args):
        """
        Returns an type of iterable1 value, which merged after iterable1 used *args
    
        :exception TypeError: if any parameter type of args not equals type(iterable1)
    
        """
    
        result_list = list(iterable1) if not isinstance(iterable1, dict) else eval('list(iterable1.items())')
    
        for i, other in enumerate(args, start=1):
            if not isinstance(other, type(iterable1)):
                raise TypeError('the parameter type of index {} not equals type of index 0'.format(i))
            if not isinstance(other, dict):
                result_list[len(result_list):len(result_list)] = list(other)
            else:
                result_list[len(result_list):len(result_list)] = list(other.items())
    
        if isinstance(iterable1, str):
            return ''.join(result_list)
        elif isinstance(iterable1, tuple):
            return tuple(result_list)
        elif isinstance(iterable1, dict):
            return dict(result_list)
        else:
            return result_list
  • 相关阅读:
    初学Python语言者必须理解的下划线
    Python初学者必须了解的星号(*)90%的人都不懂
    90%人不知道的Python炫技操作:合并字典的七种方法
    用Python爬取了妹子网100G的套图,值得收藏
    这种python反爬虫手段有点意思,看我怎么破解
    函数极限(上)
    数学分析--实数和数列极限--数轴
    B1046. 划拳
    B1026. 程序运行时间
    2019考研英语一 Text2分析
  • 原文地址:https://www.cnblogs.com/Vito2008/p/pyextned-merge.html
Copyright © 2011-2022 走看看