2

I'm trying to remove all spaces from the input which is list of list of lists... I don't know what to do for the "else:"

def removespace(lst):
   if type(lst) is str:
      return lst.replace(" ","")
   else:
      ?????

Example:

lst = [ apple, pie ,    [sth, [banana     , asd, [    sdfdsf, [fgg]]]]]

The output should be:

lst2 = [apple,pie,[sth,[banana,asd,[sdfdsf,[fgg]]]]] 

and what to do if the lst contains integers or floating points? I have received errors for integers.

example input :

 L = [['apple', '2 * core+1* sth'], ['pie', '1*apple+1*sugar+1*water'], ['water', 60]]
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Eakc
  • 69
  • 1
  • 1
  • 9

4 Answers4

4
def removespace(a):
    if type(a) is str:
        return a.replace(" ", "")
    elif type(a) is list:
        return [removespace(x) for x in a]
    elif type(a) is set:
        return {removespace(x) for x in a}
    else:
        return a

Here is a sample:

>>> removespace([["a ",["   "]],{"b ","c d"},"e f g"])
[['a', ['']], {'b', 'cd'}, 'efg']
  • @thg435. isinstance would be better, but I used the same code as the OP. For those who are interested : [link](http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python) –  Jan 17 '13 at 10:36
2

I'd suggest to follow EAFP and catch an exception instead of using isinstance. Also, never miss an opportunity to make a function a bit more generic:

def rreplace(it, old, new):
    try:
        return it.replace(old, new)
    except AttributeError:
        return [rreplace(x, old, new) for x in it]

Example:

a = [" foo", ["    spam", "ham"], "  bar"]
print rreplace(a, " ", "")     

Or even more generic, although that might be an overkill for your problem:

def rapply(it, fun, *args, **kwargs):
    try:
        return fun(it, *args, **kwargs)
    except TypeError:
        return [rapply(x, fun, *args, **kwargs) for x in it]

a = [" foo", ["    spam", "ham"], "  bar"]
print rapply(a, str.replace, " ", "")     
print rapply(a, str.upper)     
georg
  • 211,518
  • 52
  • 313
  • 390
0
def removespace(lst):
    if type(lst) is str:
        return lst.replace(" ","")
    else:
        return [removespace(elem) for elem in lst]



lst = [' apple', 'pie ', ['sth', ['banana', 'asd', [' sdfdsf', ['fgg']]]]] 
print removespace(lst)

prints

['apple', 'pie', ['sth', ['banana', 'asd', ['sdfdsf', ['fgg']]]]]
eumiro
  • 207,213
  • 34
  • 299
  • 261
0

Though you may experiment with recursive solution, but you can try your hand on a wonderful library Python provides, to transform a well formed Python literal from string to Python literal.

  • Just convert you list to string
  • remove any necessary spaces
  • and then reconvert to the recursive list structure using ast.literal_eval

    >>> lst = [' apple', 'pie ', ['sth', ['banana', 'asd', [' sdfdsf', ['fgg']]]]]
    >>> import ast
    >>> ast.literal_eval(str(lst).translate(None,' '))
    ['apple', 'pie', ['sth', ['banana', 'asd', ['sdfdsf', ['fgg']]]]]
    
Abhijit
  • 62,056
  • 18
  • 131
  • 204