(Nov-26-2020, 09:30 PM)quest_ Wrote: do not worry number of elements in my list will be always divided by 10
I am not the one who should be worrying .
So, I do not worry and ignore items which don't fit into group of 10 items (i.e. if there is 31 items only 30 are considered and last one will be ignored).
My approach would be to create grouper generator function in a such way that it ignores items at the end not fitting into groupsize (don't worry, be happy):
def grouper(iterable, groupsize): args = [iter(iterable)] * groupsize yield from zip(*args)Now I can call it with needed groupsize and perform calculations on groups as I see fit. I can create another helper function to perform some magic needed:
def group_magic(group): return [item / sum(group) for item in group]Now I am ready to do some group_magic:
[group_magic(group) for group in grouper(b, 10)]Of course, if one wants to hide magic from user, it all can be put into one function:
def do_magic(iterable, groupsize): def grouper(iterable, groupsize): args = [iter(iterable)] * groupsize yield from zip(*args) def group_magic(group): yield from (item / sum(group) for item in group) return [[*group_magic(group)] for group in grouper(iterable, groupsize)] print(do_magic(b, 10)) -> [[0.0, 0.2, 0.0, 0.2, 0.0, 0.2, 0.0, 0.2, 0.0, 0.2], [0.0, 0.2, 0.0, 0.2, 0.0, 0.2, 0.0, 0.2, 0.0, 0.2], [0.0, 0.2, 0.0, 0.2, 0.0, 0.2, 0.0, 0.2, 0.0, 0.2], [0.0, 0.2, 0.0, 0.2, 0.0, 0.2, 0.0, 0.2, 0.0, 0.2]]Then I can look at this code and say 'nah, i don't actually need those inner functions. It's too obvious what is going on, let's do some obfuscation' and write this (it returns the same as do_magic):
def do_magic_2(iterable, groupsize): groups = zip(*[iter(iterable)] * groupsize) operations = ((item / sum(group) for item in group) for group in groups) return [[*operation] for operation in operations]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.