diff options
author | Jesusaves <cpntb1@ymail.com> | 2020-12-09 13:32:01 -0300 |
---|---|---|
committer | Jesusaves <cpntb1@ymail.com> | 2020-12-09 13:32:01 -0300 |
commit | 63afe4145f410a844c647d4e3f1059f568175c1e (patch) | |
tree | 15da6a890c78d73370f44f9fd5d59badfbbe60e4 /game/python-extra/utils/lists.py | |
download | client-init.tar.gz client-init.tar.bz2 client-init.tar.xz client-init.zip |
Initial commit, forked from Spheresinit
Diffstat (limited to 'game/python-extra/utils/lists.py')
-rw-r--r-- | game/python-extra/utils/lists.py | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/game/python-extra/utils/lists.py b/game/python-extra/utils/lists.py new file mode 100644 index 0000000..aacffdb --- /dev/null +++ b/game/python-extra/utils/lists.py @@ -0,0 +1,42 @@ +"""List-related functions""" + + +def unlist(list_thing, complain=True): + """transforms [Something] -> Something. By default, raises a ValueError for + any other list values.""" + if complain and len(list_thing) > 1: + raise ValueError("More than one element in {}".format(list_thing)) + elif len(list_thing) == 1: + return list_thing[0] + + if complain: + raise ValueError("Nothing in {}".format(list_thing)) + return None + + +def flatten(iterable): + """Fully flattens an iterable: + In: flatten([1,2,3,4,[5,6,[7,8]]]) + Out: [1,2,3,4,5,6,7,8] + """ + container = iterable.__class__ + + placeholder = [] + for item in iterable: + try: + placeholder.extend(flatten(item)) + except TypeError: + placeholder.append(item) + + return container(placeholder) + + +def flat_map(iterable, func): + """func must take an item and return an interable that contains that + item. this is flatmap in the classic mode""" + results = [] + for element in iterable: + result = func(element) + if len(result) > 0: + results.extend(result) + return results |