I have a list of numbers such as [16, 17, 19, 20, 22, 23, 24, 26, 28, 29, 31, 32]. I want to separate values based on their form as an odd factor multiplied by 2^n. For example, 16, 20, 28, and 32 are divisible by 4, while numbers with different odd factors should belong to different groups. The number of groups and power-of-two levels may vary, so I would prefer a solution that creates the groups dynamically rather than using hardcoded list variables.
2 Answers
You may also want to distinguish grouping from filtering. If you only need powers of two, a number is a power of two when it is positive and has just one binary bit set: `n > 0 and (n & (n - 1)) == 0`. For dynamically grouping the whole input, you could use: `from collections import defaultdictnngroups = defaultdict(list)nnfor number in baseline:n key = numbern while key % 2 == 0:n key //= 2n groups[key].append(number)nnprint(dict(groups))`. The dictionary keys are the odd factors, and each value is the list of original numbers sharing that factor. If you want the groups ordered, use `dict(sorted(groups.items()))`.
A dictionary works well here. For each number, repeatedly divide by 2 until the remaining value is odd. That remaining odd value becomes the group key, and the original number gets appended to that key's list. This automatically handles any power of two, including numbers that are themselves powers of two.

That makes sense—I was thinking in terms of separate lists, but using the odd factor as a dictionary key avoids having to know the groups in advance.