diff --git a/README.md b/README.md index 3afa85392..c125ca392 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,8 @@ def spread(arg): + + ``` ```python @@ -132,6 +134,7 @@ Create a `set` from `b`, then use list comprehension to only keep values not con ```python + def difference(a, b): b = set(b) return [item for item in a if item not in b] @@ -319,6 +322,30 @@ def spread(arg): ```python spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9] ``` +### zip + +Creates a list of elements, grouped based on the position in the original lists. + +Use `max` combined with `list comprehension` to get the length of the longest list in the arguments. Loops for `max_length` times grouping elements. If lengths of `lists` vary `fill_value` is used. By default `fill_value` is `None`. + +```python + + +def zip(*args, fillvalue=None): + max_length = max([len(arr) for arr in args]) + result = [] + for i in range(max_length): + result.append([args[k][i] if i < len(args[k]) + else None for k in range(len(args))]) + return result + +``` + +``` python +zip(['a', 'b'], [1, 2], [True, False]); // [['a', 1, True], ['b', 2, False]] +zip(['a'], [1, 2], [True, False]); // [['a', 1, True], [None, 2, False]] +zip(['a'], [1, 2], [True, False], fill_value = '_'); // [['a', 1, True], ['_', 2, False]] +``` ## Credits diff --git a/snippets/deep_flatten.md b/snippets/deep_flatten.md index b4ac9e6da..71f9c9b2f 100644 --- a/snippets/deep_flatten.md +++ b/snippets/deep_flatten.md @@ -27,6 +27,8 @@ def spread(arg): + + ``` ```python diff --git a/snippets/difference.md b/snippets/difference.md index 32c8db200..1dd327304 100644 --- a/snippets/difference.md +++ b/snippets/difference.md @@ -6,6 +6,7 @@ Create a `set` from `b`, then use list comprehension to only keep values not con ```python + def difference(a, b): b = set(b) return [item for item in a if item not in b] diff --git a/snippets/zip.md b/snippets/zip.md new file mode 100644 index 000000000..62ff3685e --- /dev/null +++ b/snippets/zip.md @@ -0,0 +1,24 @@ +### zip + +Creates a list of elements, grouped based on the position in the original lists. + +Use `max` combined with `list comprehension` to get the length of the longest list in the arguments. Loops for `max_length` times grouping elements. If lengths of `lists` vary `fill_value` is used. By default `fill_value` is `None`. + +```python + + +def zip(*args, fillvalue=None): + max_length = max([len(arr) for arr in args]) + result = [] + for i in range(max_length): + result.append([args[k][i] if i < len(args[k]) + else None for k in range(len(args))]) + return result + +``` + +``` python +zip(['a', 'b'], [1, 2], [True, False]); // [['a', 1, True], ['b', 2, False]] +zip(['a'], [1, 2], [True, False]); // [['a', 1, True], [None, 2, False]] +zip(['a'], [1, 2], [True, False], fill_value = '_'); // [['a', 1, True], ['_', 2, False]] +``` \ No newline at end of file