How to convert list of lists (tuples) to string in python with nice delimiters
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 functiondef 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?
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! :)
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]'.
精彩评论