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
  • 相关阅读:
    白兔的字符串(字符串hash+模拟map)
    [TJOI2013]单词(AC自动机+前缀和维护)
    [SDOI2014]数数(ac自动机+数位DP)
    阿狸的打字机(AC自动机+dfs序 + 维护区间值)
    string(AC自动机 在线询问转离线询问)
    E
    JMX超详细解读
    快速生成100万数据人员信息数据
    聊聊spring之bean对象的实例化过程
    聊聊spring之贯穿全局的重要对象BeanDefinition
  • 原文地址:https://www.cnblogs.com/Vito2008/p/pyextned-merge.html
Copyright © 2011-2022 走看看