Checking length of each argument - seems like I'm fighting Python
Alex Martelli
aleax at mail.comcast.net
Sat Dec 3 19:35:48 EST 2005
Brendan <spam4bsimons at yahoo.ca> wrote:
...
> def sLen(x):
> """determines the number of items in x.
> Returns 1 if x is a scalar. Returns 0 if x is None
> """
> xt = numeric.array(x)
> if xt == None:
> return 0
> elif xt.rank == 0:
> return 1
> else:
> return xt.shape[0]
Simpler:
def sLen(x):
if x is None: return 0
try: return len(x)
except TypeError: return 1
Depending on how you define a "scalar", of course; in most applications,
a string is to be treated as a scalar, yet it responds to len(...), so
you'd have to specialcase it.
Alex
More information about the Python-list
mailing list