projects
/
python_utils.git
/ blobdiff
commit
grep
author
committer
pickaxe
?
search:
re
summary
|
shortlog
|
log
|
commit
|
commitdiff
|
tree
raw
|
inline
| side by side
Logging + documentation.
[python_utils.git]
/
list_utils.py
diff --git
a/list_utils.py
b/list_utils.py
index 74f1cf3078457d371194deb33ddf5ad6410ed599..993ca8af9ca9f9a633c02162e0f155fd3b3cab74 100644
(file)
--- a/
list_utils.py
+++ b/
list_utils.py
@@
-5,19
+5,48
@@
from typing import Any, Iterator, List
def shard(lst: List[Any], size: int) -> Iterator[Any]:
def shard(lst: List[Any], size: int) -> Iterator[Any]:
- """Yield successive size-sized shards from lst."""
+ """
+ Yield successive size-sized shards from lst.
+
+ >>> for sublist in shard([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 3):
+ ... [_ for _ in sublist]
+ [1, 2, 3]
+ [4, 5, 6]
+ [7, 8, 9]
+ [10, 11, 12]
+
+ """
for x in range(0, len(lst), size):
yield islice(lst, x, x + size)
def flatten(lst: List[Any]) -> List[Any]:
for x in range(0, len(lst), size):
yield islice(lst, x, x + size)
def flatten(lst: List[Any]) -> List[Any]:
- """Flatten out a list:
+ """
+ Flatten out a list:
+
+ >>> flatten([ 1, [2, 3, 4, [5], 6], 7, [8, [9]]])
+ [1, 2, 3, 4, 5, 6, 7, 8, 9]
- >>> flatten([ 1, [2, 3, 4, [5], 6], 7, [8, [9]]])
- [1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
if len(lst) == 0:
return lst
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])
"""
if len(lst) == 0:
return lst
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])
+
+
+def prepend(item: Any, lst: List[Any]) -> List[Any]:
+ """
+ Prepend an item to a list.
+
+ >>> prepend('foo', ['bar', 'baz'])
+ ['foo', 'bar', 'baz']
+
+ """
+ lst.insert(0, item)
+ return lst
+
+
+if __name__ == '__main__':
+ import doctest
+ doctest.testmod()