Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic conversion to singleton iterable if not already an iterable

Tags:

python

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).

like image 558
andrewgazelka Avatar asked Apr 10 '19 16:04

andrewgazelka


2 Answers

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
like image 120
wim Avatar answered Oct 21 '22 19:10

wim


You can use numpy:

np.atleast_1d(1)
# array([1])

np.atleast_1d([1,2,3])
# array([1,2,3])
like image 2
Nic Scozzaro Avatar answered Oct 21 '22 19:10

Nic Scozzaro