tgoop.com/Python4all_pro/1754
Create:
Last Update:
Last Update:
🔟 single-line functions useful for advanced Python developers:
1. We unfold the invested lists of any depth
flatten = lambda lst: [x for sub in lst for x in (flatten(sub) if isinstance(sub, list) else [sub])]
2. Decorator for memoization of the results of the function
memoize = lambda f: (lambda *args, _cache={}, **kwargs: _cache.setdefault((args, tuple(kwargs.items())), f(*args, **kwargs)))
3. Missing the list into pieces of length n
chunked = lambda lst, n: [lst[i:i+n] for i in range(0, len(lst), n)]
4. Uniqueization of the sequence with the preservation of order
uniq = lambda seq: list(dict.fromkeys(seq))
5. Deep access to the invested dictionary keys
deep_get = lambda d, *keys: __import__('functools').reduce(lambda a, k: a.get(k) if isinstance(a, dict) else None, keys, d)
6. Transformation of the Python object to the readable json
pretty_json = lambda obj: __import__('json').dumps(obj, ensure_ascii=False, indent=2)
7. Reading the latest n lakes of the file (analogue Tail)
tail = lambda f, n=10: list(__import__('collections').deque(open(f), maxlen=n))
8. Performing shell team and return of the withdrawal
sh = lambda cmd: __import__('subprocess').run(cmd, shell=True, check=True, capture_output=True).stdout.decode().strip()
9. Quick route association
path_join = lambda *p: __import__('os').path.join(*p)
10. Grouping of the list of dictionaries by key value
group_by = lambda seq, key: {k: [d for d in seq if d.get(key) == k] for k in set(d.get(key) for d in seq)}