unpack (iterable, count, fill=None)
参数:
iterable: 实现 __iter__的可迭代对象, 如 str, tuple, dict, list
count: 需要拆分的数量, 如数值大于 len(iterable) 则使用 fill 的值进行后续填充
fill: 默认值填充
使用范例:
Example 1: In[1]: source = 'abc' In[2]: a, b = unpack(source, 2) In[3]: print(a, b) a b Example 2: In[1]: source = 'abc' In[2]: a, b, c, d = unpack(source, 4) In[3]: print(a, b, c, d) a b None None
代码:
@accepts(iterable='__iter__', count=int) def unpack(iterable, count, fill=None): """ The iter data unpack function. """ iterable = list(enumerate(iterable)) cnt = count if count <= len(iterable) else len(iterable) results = [iterable[i][1] for i in range(cnt)] # results[len(results):len(results)] = [fill for i in range(count-cnt)] results = merge(results, [fill for i in range(count-cnt)]) return tuple(results)