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?

Bertrand Marron
  • 21,501
  • 8
  • 58
  • 94
Max Mayzel
  • 25
  • 5

2 Answers2

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! :)

Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
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]'.

Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52