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, '')
self.assertEqual(result, 'abc123') result = merge(source, '', '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': ''})
self.assertEqual(result, {'a': 1, 'b': 2, 'c': 3, 'x': 'm', 'y': 'n', 'z': ''})

代码:

@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
05-27 20:11