1

I have nested lists.in this lists, every nested list contains two component and each component may contain blank (' ') character.I wanted to delete and wrote a piece of code but couldn't make it work.How can i overcome this problem ?

the nested List of List is :

[['bike', '2 * wheel+1* frame'], ['wheel', '1  * rim + 1* spoke +1 *hub'], ['rim', 60], ['spoke', 120], ['hub', '2*gear+1*axle'], ['gear', 25], ['axle', '5*bolt+7*nut'],['bolt',0.1], ['nut', 0.15],['frame', '1*rearframe+ 1*frontframe'],['rearframe', 175],['frontframe', '1*fork+2*handle'], ['fork', 22.5],['handle', 10.0]]

As seen there are some blanks in some strings.

The python code i wrote :

def blanks(des):
    a = 0
    while a < len(des): 
        if type(des[0][1]) == str: 
            des[0][0] = des[0][0].replace(' ','')
        if type(des[0][1]) == str:
            des[0][1] = des[0][1].replace(' ','')
        a += 1

    return des 
  • use isinstance() instead of type(..) == str –  Jan 12 '13 at 09:21
  • Format your example data properly and write exactly what you want. –  Jan 12 '13 at 09:22
  • 1
    Neither code nor data nor question make much sense. –  Jan 12 '13 at 09:25
  • It seems that he just wants to get rid of all spaces in Strings present in his nested list. so `'2 * wheel+1* frame'` becomes `'2*wheel+1*frame'`, and so on. – Sanchit Jan 12 '13 at 09:27
  • Is the nesting level fixed or variable ? – asheeshr Jan 12 '13 at 09:28
  • I am not guessing what OP thinks what this code must do. SO is not the guess-my-code game. –  Jan 12 '13 at 09:31
  • sanchit, you are true about expected result, AshRj, there is no fixed list level. @CRUSADER i excuse about my post but others understood.thanks for your effort. –  Jan 12 '13 at 09:37
  • There, @kycklysf I made a very generic solution that removes spaces from nested lists. and yes CRUSADER you are correct, the guessing game is generally bad. – Sanchit Jan 12 '13 at 10:01

5 Answers5

1

Use a for loop instead.

def blanks(lis):
    for i, _ in enumerate(lis):
        for j in range(2):
            if isinstance(lis[i][j], str):
                lis[i][j] = lis[i][j].replace(' ', '')
    return lis

A list comprehension would work as well.

def blanks(lis):
    return [i.replace(' ', '') if isinstance(i, str) else i for a in lis for i in a]

Or just without the function definition:

lis = [[i.replace(' ', '') if isinstance(i, str) else i for i in a] for a in lis]

I think this should do what you want. If however, your nested list has an inconsistent depth, you would be better off using a generator function.

def blanks(lis):
    for i, el in enumerate(lis):
        if isinstance(el, list):
            blanks(el)
        elif isinstance(el, str):
            yield el.replace(' ', '')
        else:
            yield el

See also this answer for more information on the last piece of code.

Community
  • 1
  • 1
Volatility
  • 31,232
  • 10
  • 80
  • 89
0

This would be one way to do:

map(lambda x:map(lambda y:y.replace(' ','') if isinstance(y,str) else y,x),a)

where a is the input list which you pass on.

Sibi
  • 47,472
  • 16
  • 95
  • 163
0

Okay so since there isn't a limit or any fixed parameters you will have to use a little bit of recursion to solve your problem.

def trimSpaces(list):
  for i in range(0,len(list)):
    if type(list[i]) == str:
      list[i] = list[i].replace(' ','')
    elif type(list[i]) == type([]):
      list[i] = trimSpaces(list[i])
    else:
      continue
  return list
Sanchit
  • 2,240
  • 4
  • 23
  • 34
0

Try this:

def removeBlanks(input):

  if type(input) is list:
    ret=[]
    for i in input:
      ret.append(removeBlanks(i))
  else:
    ret=input.replace(" ", "")

  return ret   
Ruediger Jungbeck
  • 2,836
  • 5
  • 36
  • 59
0

In python, you usually want to follow EAFP and catch exceptions instead of prevalidiating input with isinstance:

def no_blanks(s):
    try:
        return s.replace(' ', '')
    except AttributeError:
        return s

ls = [['bike', '2 * wheel+1* frame'], ['wheel', '1  * rim + 1* spoke +1 *hub'], ['rim', 60], ['spoke', 120], ['hub', '2*gear+1*axle'], ['gear', 25], ['axle', '5*bolt+7*nut'],['bolt',0.1], ['nut', 0.15],['frame', '1*rearframe+ 1*frontframe'],['rearframe', 175],['frontframe', '1*fork+2*handle'], ['fork', 22.5],['handle', 10.0]]

new_ls = [[no_blanks(a), no_blanks(b)] for a, b in ls]

Also looking at your list closely it seems to me that dict would be perhaps a better choice for your data.

georg
  • 211,518
  • 52
  • 313
  • 390
  • @kycklysf: just out of interest, are you building something similar to http://stackoverflow.com/q/14273581/989121 ? – georg Jan 12 '13 at 10:28
  • @kycklysf: in this case I'd suggest using nested dictionaries instead of strings, like `{'bike': {'wheel':2, 'frame':1}, 'wheel': {'rim':1` etc – georg Jan 12 '13 at 10:35
  • actually i want to do http://stackoverflow.com/questions/14101633/how-to-convert-a-list-to-a-tree-in-python?rq=1 how an algorithm would you suggest ? –  Jan 12 '13 at 10:39
  • @kycklysf: you'd better ask a new question about that (but try something on your own first). – georg Jan 12 '13 at 10:42
  • by my question i get an blank-removed nested lists, then my purpose is to convert a list to a tree as same as the link above. –  Jan 12 '13 at 10:42
  • thank you, of course, before posting i will put my effort on it. –  Jan 12 '13 at 10:44