1

What is the best way to convert list of lists/tuples to string with incremental indents.
So far I've ended up with such a function

def a2s(a, inc = 0):
    inc += 1
    sep = ' ' * inc
    if type(a) == type(list()) or type(a) == type(tuple()):
        a = sep.join(map(a2s, a))
    else:
       a = str(a)
   return a

It would give

>>> a=[[1, 2], [3, 4]]
>>> a2s(a)
'1 2 3 4'

So the question is how to make increment between [1,2] and [3,4] larger, like this

>>> a2s(a)
'1 2  3 4'

If there any way to pass non-iterable 'inc' argument through the map function? Or any other way to do that?

3
  • Check out this post : Python - convert list of tuples to string Commented Jun 14, 2011 at 10:48
  • You can just use is type(a) == list. And even better: isinstance(a, collections.Iterable) Commented Jun 14, 2011 at 10:49
  • sorry, I mean this post :stackoverflow.com/questions/3292643/… Commented Jun 14, 2011 at 11:00

2 Answers 2

0

Here is what you need:

import collections

def a2s(a):
    res = ''
    if isinstance(a, collections.Iterable):
        for item in a:
            res +=  str(a2s(item)) + ' '
    else:
        res = str(a)
    return res

Usage:

a = [ [1, 2], [3, 4] ]
print(a2s(a))
>>> 1 2  3 4

Recursion rocks! :)

Sign up to request clarification or add additional context in comments.

Comments

0

Your function can be modified the following way:

def list_to_string(lVals, spacesCount=1):
    for i,val in enumerate(lVals):
        strToApp = ' '.join(map(str, val))
        if i == 0:
            res = strToApp 
        else:
            res += ' ' * spacesCount + strToApp
    return res

print list_to_string(a)# '1 2 3 4'
print list_to_string(a,2)# '1 2  3 4'
print list_to_string(a,3)# '1 2   3 4'

OR a bit weird but:

from collections import Iterable

data = [[1, 2], [3, 4], [5,6], 7]

def list_to_string(lVals, spacesCount=3):
    joinVals = lambda vals: ' '.join(map(str, vals)) if isinstance(vals, Iterable) else str(vals)
    return reduce(lambda res, x: joinVals(res) + (' ' * spacesCount) + joinVals(x), lVals)

list_to_string(data, 4)

And it is better to use 'isinstance' instead of 'type(val) == type(list())', or you can use 'type(val) in [list, tuple, set]'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.