首页 > 其他 > 详细

pyextend库-merge可迭代对象合并函数

时间:2016-02-17 12:48:49      阅读:225      评论:0      收藏:0      [点我收藏+]

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

 

pyextend库-merge可迭代对象合并函数

原文:http://www.cnblogs.com/Vito2008/p/pyextned-merge.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!