When to use '.flat', '.flatiter' o

2020-07-09 08:57发布

问题:

When is it appropriate to use which of the three flattening arguments '.flat'/'.flatiter'/'.flatten'? I know that '.flat' returns a 1D iterator over an array, does this mean that the array is left in the original shape and each element in the array can be accessed with a single index (for example using a single for loop even though the array may be highly dimensional). And '.flatten' returns a complete copy of the original array flattened out into a 1D array.

Which is less resource intensive?

回答1:

flatiter is just the type of the iterator object returned by flat (docs). So all you need to know about it is that it's an iterator like any other.

Obviously, flatten consumes more memory and cpu, as it creates a new array, while flat only creates the iterator object, which is super fast.

If all you need is to iterate over the array, in a flat manner, use flat.

If you need an actual flat array (for purposes other than just explicitly iterating over it), use flatten.