Suppose I have
def distance2(vector1, vector2):
zipped = zip(vector1, vector2)
difference2 = [(vector2 - vector1) ** 2 for (vector1, vector2) in zipped]
return sum(difference2)
where distance2(vector1, vector2)
finds the (squared) Euclidian distance between vector1
and vector2
. The function will work for iterable elements, but suppose we also want to make it work for non-iterable elements (i.e. distance2(1,3)
). Is there a pythonic way to do this? (i.e, automatically turning regular input into a singleton list).
You are describing the basic usage of always_iterable
.
>>> from more_itertools.more import always_iterable
>>> for val in always_iterable(1):
... print(val)
...
1
You can use numpy:
np.atleast_1d(1)
# array([1])
np.atleast_1d([1,2,3])
# array([1,2,3])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With