Python: Treating A Scalar As A One Element List
I am writing a python script that process lists read from a file: l = readListFromFile( myFile ) for i in l : # do something to each element All works fine when l has more tha
Solution 1:
Well a simple solution is
l = readListFromFile(myFile)
try:
i = iter(l)
ifisinstance(l, str):
i = l
except TypeError:
i = [l]
for .... in i
This will work even if you change what readListFromFile
to return another iterable.
A one liner solution if it's guaranteed to be a str
or a list (or other iterable) is just
l = readListFromFile(myFile)
for e in [l] ifisinstance(l, str) else l:
just using a ternary operator.
On an aside, having a method called readList... not always returning a list is just evil.
Solution 2:
l = readListFromFile(myFile)
if isinstance(l, list):
for i in l :
# do something to each elementelse:#do that something mentioned above
or
l = readListFromFile(myFile)
ifisinstance(l, str):
l = [l]
for i in l:
#do that same something as above
or
l = readListFromFile(myFile)
try:
for i in l:
#do that somethingexcept:#do that something with the value
and if you want a function:
def get_me_a_list(var):
if isinstance(var, list):
returnvarreturn [var]
l = get_me_a_list(readListFromFile(myFile))
for i in l:
#do your something
Solution 3:
Using a generator function and isinstance
:
defsolve(lis):
ifisinstance(lis, list):
for item in lis: #use just `yield from lis` in py3.xyield item
else:
yield lis
Demo:
>>>for item in solve(1):...print item...
1
>>>for item in solve([1, 2, 3]):
print item
...
1
2
3
To handle any type of iterable you can use collections.Iterable
:
from collections import Iterable
defsolve(lis):
ifisinstance(lis, Iterable) andnotisinstance(lis, basestring):
for item in lis: #use just `yield from lis` in py3.xyield item
else:
yield lis
Solution 4:
You can put the check directly into the for-loop:
l = readListFromFile( myFile )
for i in (l if isinstance(l, list) else [l]):
# Do something with i
Solution 5:
If readFromFile
returns a scalar rather than a list
, then you can turn it to a list
by yourself.
l = readListFromFile( myFile )
if not isinstance(l, list):
l = [l]
for i in l :
# do something to each element
Post a Comment for "Python: Treating A Scalar As A One Element List"