mirror of
https://github.com/donnemartin/data-science-ipython-notebooks.git
synced 2024-03-22 13:30:56 +08:00
Added snippet to convert an object to a list. Useful when writing functions that can accept multiple types of
input (list, tuple, ndarray, iterator).
This commit is contained in:
parent
52552208c1
commit
4c94ff5948
|
@ -39,3 +39,7 @@ class TestUtil():
|
|||
def test_is_iterable(self):
|
||||
assert_equal(Util.is_iterable('foo'), True)
|
||||
assert_equal(Util.is_iterable(7), False)
|
||||
|
||||
def test_convert_to_list(obj):
|
||||
assert_equal(isinstance(Util.convert_to_list('foo'), list), True)
|
||||
assert_equal(isinstance(Util.convert_to_list(7), list), False)
|
10
util.py
10
util.py
|
@ -7,3 +7,13 @@ class Util:
|
|||
return True
|
||||
except TypeError:
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def convert_to_list(self, obj):
|
||||
"""Useful when writing functions that can accept multiple types of
|
||||
input (list, tuple, ndarray, iterator). Checks if the object is a list.
|
||||
If it is not a list, converts it to a list.
|
||||
"""
|
||||
if not isinstance(obj, list) and self.is_iterable(obj):
|
||||
obj = list(obj)
|
||||
return obj
|
||||
|
|
Loading…
Reference in New Issue
Block a user